If I have an object of a certain type, and I would like to get the unbound method, should I use type(obj).method_name
or obj.__class__.method_name
? I got confused upon seeing the following result:
class ClassA(object):
def Test(self):
pass
obj_a = ClassA()
print obj_a.__class__ is type(obj_a)
print obj_a.__class__.Test is type(obj_a).Test
The first returns True and the second False. So what is the difference of the two in the last statement?
UPDATE:
My use case is that I have some class in a playground notebook. The class objects may be heavy, for example, they contain stuff after long time of training. During the time I would like to make updates to the functions and keep use the existing objects. So I would like something like this to be working:
# In cell 1 I define the following class.
class ClassA(object):
def Test(self):
print 'haha'
# In cell 2 I create an object and use it for a while.
obj_a = ClassA()
obj_a.Test()
# After some time I modified the ClassA in cell 1 and re-executed the cell:
class ClassA(object):
def Test(self):
print 'hoho'
# Then I want to replace a method and call Test again:
obj_a.__class__.Test = ClassA.Test
obj_a.Test() # Should print 'hoho'
Unfortunately the above code does not work. The last call obj_a.Test()
uses the unbound method Test
.