Python - why can I call a class method with an instance? -
new python , having done reading, i'm making methods in custom class class methods rather instance methods.
so tested code hadn't changed of method calls call method in class rather instance, still worked:
class myclass: @classmethod: def foo(cls): print 'class method foo called %s.'%(cls) def bar(self): print 'instance method bar called %s.'%(self) myclass.foo() thing = myclass() thing.foo() thing.bar()
this produces:
class method foo called __main__.myclass. class method foo called __main__.myclass. instance method bar called <__main__.myclass instance @ 0x389ba4>.
so i'm wondering why can call class method (foo) on instance (thing.foo), (although it's class gets passed method)? kind of makes sense, 'thing' 'myclass', expecting python give error saying along lines of 'foo class method , can't called on instance'.
is expected consequence of inheritance 'thing' object inheriting foo method it's superclass?
if try call instance method via class:
myclass.bar()
then get:
typeerror: unbound method bar() must called myclass instance...
which makes perfect sense.
you can call on instance because @classmethod
decorator (it takes function argument , returns new function).
here relavent information python documentation
it can called either on class (such c.f()) or on instance (such c().f()). instance ignored except class. if class method called derived class, derived class object passed implied first argument.
there's quite discussion on @classmethod
here.
Comments
Post a Comment