好吧,再一次,这不是你应该通常做的,这是仅供参考的目的。
其中Python在实例对象上寻找一个方法是由定义该对象的类的__mro__属性决定的(M ethod R esolution O rder属性)。因此,如果我们可以修改Person的__mro__,我们会得到所需的行为。就像是:
setattr(Person, '__mro__', (Person, Friendly, object))
问题是__mro__是一个只读属性,因此setattr将不工作。也许如果你是一个Python大师有一个方法,但显然我缺乏大师的地位,因为我不能想到一个。
一个可能的解决方法是简单地重新定义类:
def modify_Person_to_be_friendly():
# so that we're modifying the global identifier 'Person'
global Person
# now just redefine the class using type(), specifying that the new
# class should inherit from Friendly and have all attributes from
# our old Person class
Person = type('Person', (Friendly,), dict(Person.__dict__))
def main():
modify_Person_to_be_friendly()
p = Person()
p.hello() # works!
这不是修改任何以前创建的Person实例以具有hello()方法。例如(只是修改main()):
def main():
oldperson = Person()
ModifyPersonToBeFriendly()
p = Person()
p.hello()
# works! But:
oldperson.hello()
# does not