Search code examples
pythonclassclass-method

Advantage of using @classmethod instead of type(self) in Python?


Is there an advantage in using a @classmethod (and cls) instead of type(self) to instantiate classes?

For example, an abstract class contains a normal method which at some point instantiates an instance of the sub-class whose instance calls that method. So the call to type(self) (located inside a method in the abstract base class) would be a call to the sub-class (same as, I suppose, would be if using @classmethod).

class M(ABC):
    ...
    def simple_method(self):
        'Do stuff & return new instance'
        return type(self)()

    @classmethod
    def cls_method(cls):
        return cls()

class A(M):
    ...

a = A()
b = a.simple_method()
c = a.cls_method()

It appears to me easier and more flexible to use type(self) than @classmethod. Is there anything against this practice or cases where it should be avoided?


Solution

  • In the first case you are evaluating type of the object and then creating an object out of it which will be slower than using classmethod because cls is directly passed down to the function and there is no need to evaluate the type. Another difference is that to invoke a classmethod you do not need the object of that class to be initialized you can directly invoke it using A.cls_method()