In the last line of my code, I'm able to use
__get__
with b object and instance:type(b)
. This only works if methodb
is defined inclass B
. Why is it so?
You have to define a method b
in class B
, because in A.b
you have print self.b
. Here, self
is an instance of the B class, so self.b
means "the b
method belonging to this B
", not "the b
method belonging to the class that this method exists in". If you delete print self.b
, then the code will work even if B
has no b
.
Even though the last line requires me to provide a method
b
inclass B
, still the methodb
inclass A
gets called. Why is it so?
A.b
is being called because you are explicitly accessing it with type( o ).__dict__['b']
. Whether you bind that method to an A instance or a B instance doesn't matter; it's still A.b
.
To my utter surprise, after the above step, I notice that the method
a
ofclass A
is not called by the code of methodb
ofclass A
; instead, it calls the methoda
ofclass B
. Why is it so?
Even though b
belongs to the class A
, the self
you pass to it is still an instance of the B
class. Any attributes you access on that self
will be B
attributes, and any methods you call on it will be B
methods.