gpt4 book ai didi

python - 如何扩充 Python 对象的方法?

转载 作者:太空狗 更新时间:2023-10-30 02:23:23 25 4
gpt4 key购买 nike

我有一个垃圾邮件对象列表:

class Spam:
def update(self):
print('updating spam!')

其中一些可能是 SpamLite 对象:

class SpamLite(Spam):
def update(self):
print('this spam is lite!')
Spam.update(self)

我希望能够从列表中获取任意对象,并向它的更新方法添加一些内容,例如:

def poison(spam):
tmp = spam.update
def newUpdate(self):
print 'this spam has been poisoned!'
tmp(self)
spam.update = newUpdate

我希望 spam.update() 现在打印:

this spam has been poisoned!
updating spam!

this spam has been poisoned!
this spam is lite!
updating spam!

取决于它是 SpamLite 还是垃圾邮件。

但这不起作用,因为 spam.update() 不会自动传入 self 参数,并且因为如果 tmp 离开作用域或发生更改,那么它不会调用旧的更新。我有办法做到这一点吗?

最佳答案

def poison(spam):
tmp = spam.update
def newUpdate():
print 'this spam has been poisoned!'
tmp()
spam.update = newUpdate

完整脚本:

class Spam:
def update(self):
print('updating spam!')

class SpamLite(Spam):
def update(self):
print('this spam is lite!')
Spam.update(self)

def poison(spam):
tmp = spam.update # it is a bound method that doesn't take any arguments
def newUpdate():
print 'this spam has been poisoned!'
tmp()
spam.update = newUpdate


from operator import methodcaller
L = [Spam(), SpamLite()]
map(methodcaller('update'), L)
map(poison, L)
print "*"*79
map(methodcaller('update'), L)

输出:

updating spam!this spam is lite!updating spam!*******************************************************************************this spam has been poisoned!updating spam!this spam has been poisoned!this spam is lite!updating spam!

关于python - 如何扩充 Python 对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4243586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com