0

I am learning about classmethod. I have looked at this example

class A(object):
    def foo(self,x):
        print (self,x)

    @classmethod
    def class_foo(cls,x):
        print(cls,x)

    @staticmethod
    def static_foo(x):
        print (x)   

a=A()
a.foo('pic')
a.class_foo('pic')

This is output

<__main__.A object at 0x7f413121c080> pic
<class '__main__.A'> pic

What is the practical meaning of this?Implementation?

Simke
  • 7
  • 4
  • 5
    The first is the default string representation of an object (whose type is `__main__.A`). The second is the default string representation of the class `__main__.A`. – khelwood Mar 02 '18 at 10:41
  • `"__main__"` is the name of the current module in the repl or in a script. If you imported the class from a file called `foobar.py`, the class would be represented as `foobar.A` instead of `__main__.A`. Pretty useful for debugging to know where the class was defined. – Håken Lid Mar 02 '18 at 11:26

1 Answers1

1

Implementation-wise, a classmethod takes the first obligatory cls argument, which is not the case for a staticmethod.

The practical meaning is that you can call a classmethod without having to create a class object first. In code this is perfectly valid:

A.class_foo('pic')

You can read more about this subject on this excellent SO post.

kingJulian
  • 5,601
  • 5
  • 17
  • 30