Jua*_*ipe 5 python attributes overwrite new-operator
我正在使用一个 3rd 方库,该库对某个类的重现性很差,一旦创建了该类的实例,我想覆盖它。
我看到了如何在现有对象中创建绑定方法。
class toy():
pass
inst= toy()
class inhtoy():
def __new__(cls,obj):
def __repr__(self):
return 'Sucessful'
import types
obj.__repr__ = types.MethodType(__repr__,obj)
return obj
t = inhtoy(inst)
Run Code Online (Sandbox Code Playgroud)
确实,如果我调用 t. repr () 它可以工作,但是它不会覆盖原始repr。它表现为<bound method inhtoy.__new__.<locals>.__repr__ of <__main__.toy object at 0x7f76e0b61f98>>
一种局部方法。
调用repr(t)仍然指向原始表示'<__main__.toy object at 0x7f76e0b61f98>'而不是被覆盖的表示。
有没有办法正确地做到这一点?
谢谢
环顾四周后我找到了这个答案。在实时实例上执行此操作的方法是:
t.__class__.__repr__ = my_custom_repr
Run Code Online (Sandbox Code Playgroud)
请注意,这会更改所有类实例,而不仅仅是此实例
| 归档时间: |
|
| 查看次数: |
2686 次 |
| 最近记录: |