3 回答

TA貢獻(xiàn)1789條經(jīng)驗 獲得超10個贊
好的,再次,這不是您通常應(yīng)該執(zhí)行的操作,僅用于提供信息。
其中的Python查找一個實例對象的方法是由確定__mro__它定義了對象(該類的屬性中號 ethod ? esolution ?刻申屬性)。因此,如果我們能夠改變__mro__的Person,我們會得到期望的行為。就像是:
setattr(Person, '__mro__', (Person, Friendly, object))
問題是這__mro__是一個只讀屬性,因此setattr將不起作用。也許如果您是Python專家,那么可以采取一些措施,但顯然我沒有達(dá)到專家地位,因為我想不到。
一個可能的解決方法是簡單地重新定義該類:
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!
這不做的是修改任何先前創(chuàng)建的Person實例以使用該hello()方法。例如(僅修改main()):
def main():
oldperson = Person()
ModifyPersonToBeFriendly()
p = Person()
p.hello()
# works! But:
oldperson.hello()
# does not
如果type調(diào)用的細(xì)節(jié)不清楚,請閱讀e-satis關(guān)于“ Python中的元類是什么?”的出色答案。。

TA貢獻(xiàn)1827條經(jīng)驗 獲得超4個贊
我不能保證后果,但是這段代碼可以滿足您在py2.7.2上的要求。
class Friendly(object):
def hello(self):
print 'Hello'
class Person(object): pass
# we can't change the original classes, so we replace them
class newFriendly: pass
newFriendly.__dict__ = dict(Friendly.__dict__)
Friendly = newFriendly
class newPerson: pass
newPerson.__dict__ = dict(Person.__dict__)
Person = newPerson
p = Person()
Person.__bases__ = (Friendly,)
p.hello() # prints "Hello"
我們知道這是可能的。涼。但是我們永遠(yuǎn)不會使用它!
添加回答
舉報