首页 > 解决方案 > Python将属性的属性添加到类的实例

问题描述

我正在尝试使用属性重新定义对象的属性

class MyClass:
    asd = 'asd_string'

    @property
    def foo(self):
        return 1 if self.asd is not None else None


def execute(obj):
    print(obj.bar)


if __name__ == '__main__':
    obj = MyClass()
    obj.bar = 42
    execute(obj) # 42
    
    obj.bar = property(fget=lambda self: 1 if self.asd is not None else None)
    
    execute(obj) # <property object at 0x7fd058ef7400>

我想bar用类似于def foo The question, I cannot editMyClass和 a cannot change the executefunction 的东西重新定义另外,我不确定 lambda 是否可以与 self(instance of MyClass)一起使用

是否可以在运行时使用选项修补对象?

标签: python

解决方案


您可以将新属性添加MyClass到实例中

prop = property(fget=lambda self: 1 if self.asd is not None else None)
setattr(MyClass, 'bar', prop)
# or
MyClass.bar = prop

execute(obj) # 1

推荐阅读