小编Jua*_*ipe的帖子

如何为已经实例化的类 python 覆盖 __repr__ 方法

我正在使用一个 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>'而不是被覆盖的表示。

有没有办法正确地做到这一点?
谢谢

python attributes overwrite new-operator

5
推荐指数
1
解决办法
2686
查看次数

标签 统计

attributes ×1

new-operator ×1

overwrite ×1

python ×1