Reputation: 2641
class A(object):
def a(self, b=1):
print 'Up'
d = {1 : a}
def b( self ):
print self.d[1]
print self.b
print self.d[1].__get__( self, A )()
# print self.d[1]()
class B( object ):
def a( self ):
print 'here??'
return 10000
d = {1 : a}
def b( self ):
print 'hurray'
o = A()
o.b()
b = B()
type( o ).__dict__['b'].__get__( b, type( b ) )()
Hi Folks,
I was going through Python: Bind an Unbound Method? and http://users.rcn.com/python/download/Descriptor.htm and trying to experiment on my learning.
But, I have hit some new doubts now:-
__get__
with b
object and instance: type(b)
. This only works if method b
is defined in class B
. Why is it so?b
in class B
, still the method b
in class A
gets called. Why is it so?a
of class A
is not called by the code of method b
of class A
; instead, it calls the method a
of class B
. Why is it so?I'm quite confused after seeing this behaviour. I might also need to learn more on descriptors. But, it would be a great help if you could answer my doubts
Upvotes: 2
Views: 140
Reputation: 76194
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.
Upvotes: 2