Python add attribute of property to instance of class

Viewed 62

I am trying to redefine attribute for the object with property

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>

I would like to redefine bar with something similar to def foo The problem, I cannot edit MyClass, and a cannot change the execute function Also, I am not sure that lambda will work with self(instance of MyClass)

Is it possible at all to patch the object with options during run time?

1 Answers

You can add the new property to MyClass instead to the instance

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
Related