如何更新现有对象中的类类型和方法

时间:2016-02-28 06:17:20

标签: python

如果我有某种类型的对象,并且我想获得未绑定的方法,我应该使用type(obj).method_name还是obj.__class__.method_name?看到以下结果后我感到困惑:

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 

第一个返回True,第二个返回False。那么最后一个陈述中两者的区别是什么?

更新:

我的用例是我在游乐场笔记本上有一些课。类对象可能很重,例如,它们在长时间训练后包含东西。在此期间,我想对功能进行更新并继续使用现有对象。所以我希望这样的东西能够起作用:

# 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'

不幸的是上面的代码不起作用。最后一次通话obj_a.Test()使用未绑定的方法Test

2 个答案:

答案 0 :(得分:2)

您的问题的答案,您需要分配绑定方法,例如:

import types
obj_a.Test = types.MethodType(ClassA.Test, obj_a)
obj_a.Test()

会给出您期望的结果,即'hoho'

已更新:以下是一个例子:

import types

class ClassA(object):
    def Test(self):
        print 'haha'

obj = ClassA()
obj.Test()
# haha

将ClassA更新为hoho

obj.__class__ = ClassA
obj.Test()
# hoho

答案 1 :(得分:2)

您也可以尝试:

obj_a.__class__.Test is obj_a.__class__.Test
type(obj_a).Test is type(obj_a).Test

两者都等同于ClassA.Test is ClassA.Test,但所有这些都返回False

对此的解释是无限制方法的特定行为,请参阅here