我正在努力改变课堂教学的方法。我可以使用类名更改它,如下所示:
class Foo:
def __init__(self, x):
self.x = x
def method(self):
print("original method")
return self.x
def new_method(self):
print("new method")
return self.x
Foo.method = new_method
foo = Foo(1)
print(foo.method()) # Works fine但是,我想使用对象名而不是类来更改方法,这会引发一个错误:
foo = Foo(1)
foo.method = new_method
print(foo.method()) # TypeError: new_method() missing 1 required positional argument: 'self'如能在这件事上提供任何帮助,将不胜感激
发布于 2022-09-30 14:40:47
您需要为self提供绑定。这是在类中定义方法时为您自动完成的,而不是当您对对象进行猴子修补时。
>>> foo = Foo(1)
>>> foo.method = lambda: new_method(foo)
>>> print(foo.method())
new method
1https://stackoverflow.com/questions/73910399
复制相似问题