Search code examples
pythonselfclass-method

@classmethod and method without self


Let's suppose we have this class:

class Demo:

    def __init__(self, str):
        self.str = str

    def fromBytes1(bytes):
        return Demo(bytes2str(bytes))

    @classmethod
    def fromBytes2(cls, bytes):
        return cls(bytes2str(bytes))

What is the difference between fromBytes1 and fromBytes2, except for the fact that you can't call the 1st method in the following way?

Demo().fromBytes1(bytes)

Is there something more subtle that I cannot see here?


Solution

  • Assuming that you only intend to call the methods from a class object, all the important differences are in inheritance. Say you have

    class Test(Demo):
        pass
    

    If you do Test.fromBytes1(b'ar'), you get an instance of Demo.

    If you do Test.fromBytes2(b'ar'), you get an instance of Test.

    The second method is more flexible because you can hard code Demo or __class__ into it directly, but you must hard code it in the first case.