Friday, July 25, 2008

Python Inheritance

This grid shows how methods (and any attributes) are inherited.






























This is a simplified chart and technically it's not quite correct, where lines go from left to right should not be called inheritance.

Back to Python implementation, when a method gets called from an instance, it's __get__ is called and it returns a bound method.

>>> class A(object):
... def __init__(self, name):
... self.name = name
... def printName(self):
... print self.name
...
>>> a = A('Koichi')
>>> boundmethod = A.printName.__get__(a)
>>> boundmethod
<bound method ?.printName of <__main__.A object at 0x69bf0>>
>>> boundmethod()
Koichi

This is equivalent to this.

>>> boundmethod = a.printName
>>> boundmethod
<bound method A.printName of <__main__.A object at 0x69bf0>>
>>> boundmethod()
Koichi

No comments: