是的,这是可行的。在这里,我使用functools.partial
将隐含self
参数转换为常规(非类方法)函数:
import functools
class WackyCount(object):
"it's a counter, but it has one wacky method"
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
return '%s = %d' % (self.name, self.value)
def incr(self):
self.value += 1
def decr(self):
self.value -= 1
def wacky_incr(self):
self.value += random.randint(5, 9)
# although x is a regular wacky counter...
x = WackyCount('spam', 1)
# it increments like crazy:
def spam_incr(self):
self.value *= 2
x.incr = functools.partial(spam_incr, x)
print (x)
x.incr()
print (x)
x.incr()
print (x)
x.incr()
print (x)
和:
$ python2.7 wacky.py
spam = 1
spam = 2
spam = 4
spam = 8
$ python3.2 wacky.py
spam = 1
spam = 2
spam = 4
spam = 8
编辑以添加注释:这是每个实例的覆盖。它利用了 Python 的属性查找序列:如果x
是 class 的实例K
,则x.attrname
首先查看x
的字典以查找属性。如果没有找到,下一个查找在K
. 所有正常的类函数实际上都是K.func
. 因此,如果您想动态替换类函数,请改用@Brian Cane 的答案。