- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个垃圾邮件对象列表:
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/
我正在尝试填充一个 ListView ,其中每一行都有 2 个 TextView 和一个按钮。我想我几乎让它正常工作,但现在 ListView 只显示 ListView 中的 1 个项目并忽略其他数据
是否可以通过向 DOM 元素添加新属性来扩充普通 JavaScript 对象?例如,我们能否为按钮或输入添加一个新属性,比如一个指示用户最后一次点击它的时间的值? 最佳答案 是的。有时您会发现它被描述
我的要求是能够快速检索树中的最小值和最大值。 (注意,不是最小/最大 key ,而是卫星数据的最小/最大)。 树将基于字符串作为键,每个节点将存储一个整数。这个整数必然会改变并不断更新。键保持固定 我
我正在浏览 Introduction to Algorithms by Cormen第 14 章(增强数据结构),他在其中谈论区间树。下面是他提到的区间树背后的设计方法。 Step 1: Underl
我知道如何为每个对象添加新方法 - 通过扩充对象的原型(prototype): Object.prototype.foo = function() { }; 但是,是否可以只为 DOM 元素节点定义
我正在开发一个已经在 Kaggle 实现的项目这与图像分类有关。我总共有 6 个类别要预测,分别是愤怒、快乐、悲伤等。我已经实现了 CNN 模型,目前仅使用 4 个类别(图像数量最多的类别),但我的模
在我的 NativeScript 项目中,我想包含来自 Android 支持库的 RecyclerView。我将依赖项包含在 app/App_Resources/Android/app.gradle
我正在创建一个使用 twitter api 的应用程序。 我正在检索推文并向用户展示。 在某些情况下,推文有链接,如下图所示。 阅读 twitter 的 api 文档,我发现了一个叫做“增强 URL
我正在阅读JavaScript the good parts这本书,看到了以下代码: Function.prototype.method = function (name, func) { this
我有一个按钮 View 。我是否必须将它包装在 Layout 中以便能够在 Activity 中膨胀它的实例? View 是否有类似的模式,以便我可以声明性地设置一次,然后创建它的多个实例? 谢谢。
我在数据库的 BLOB 字段中有一个 zip 流。我正在尝试给它充气,但到目前为止还做不到。 问题是这个流是一个压缩流,而不是一个完整的压缩文件。 如果清楚的话,这将是对其进行膨胀的 Java 代码:
我是一名优秀的程序员,十分优秀!