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.
Steve ives
source share