Python - why can I call a class method with an instance?

New to Python and after doing some reading, I am making some methods in my class methods of the class, and not in the instance methods.

So, I tested my code, but I did not change some method calls to call the method in the class, not the instance, but they still worked:

class myclass: @classmethod: def foo(cls): print 'Class method foo called with %s.'%(cls) def bar(self): print 'Instance method bar called with %s.'%(self) myclass.foo() thing = myClass() thing.foo() thing.bar() 

This gives:

 class method foo called with __main__.myclass. class method foo called with __main__.myclass. instance method bar called with <__main__.myclass instance at 0x389ba4>. 

So I wonder why I can call the class method (foo) on the instance (thing.foo), (although this is the class that is passed to the method)? This makes sense since the โ€œthingโ€ is โ€œmyClassโ€, but I expected Python to give an error saying something like the string โ€œfoo is a class method and cannot be called on an instanceโ€.

Is this just an expected consequence of inheritance with the thing object inheriting the foo method from this superclass?

If I try to call an instance method through a class:

 myclass.bar() 

then I get:

 TypeError: unbound method bar() must be called with myclass instance... 

which makes perfect sense.

+7
python inheritance class-method
source share
1 answer

You can call it in an instance because @classmethod is a decorator (it takes a function as an argument and returns a new function).

Here is some relevant information from the Python documentation

It can be called either in the class (for example, Cf ()), or in an instance (for example, C (). F ()). The instance is ignored, except for its class. If the class method is called for a derived class, the object of the derived class is passed as the intended first argument.

There's also a nice SO discussion on @classmethod here .

+6
source share

All Articles