3

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?

5
  • You're missing a self parameter in the first case. Also, could you give the methods slightly different names? Commented Dec 20, 2021 at 16:01
  • @MadPhysicist I thought that omission was intentional. It lets you use the method as a pseudo-static method (Demo.fromBytes(…) works), but Demo().fromBytes() does something unexpected. Commented Dec 20, 2021 at 16:05
  • I think you can define methods without self. Commented Dec 20, 2021 at 16:05
  • 3
    @igol you can but you shouldn't. Don't write something like your version 1 ever. That should just be a regular function, outside of the class. In any case, the difference is obvious, a classmethod will implicitly get passed the class as it's first positional argument Commented Dec 20, 2021 at 16:24
  • 2
    If you really want the first variant, make it an @staticmethod. Commented Dec 20, 2021 at 16:46

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

So, with @classmethod, you don't need to override the method?
@MisterMiyagi Yeah I know that. I wrote that you can't call the 1st variant with Demo().fromBytes(some_bytes)
@MisterMiyagi. Of course. I have no idea why I didn't write it that way. Will fix momentarily.
@igol. I misread. Will fix ASAP
@igol. F i x e d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.