python - 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 execute
function 的东西重新定义另外,我不确定 lambda 是否可以与 self(instance of MyClass
)一起使用
是否可以在运行时使用选项修补对象?
解决方案
您可以将新属性添加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
推荐阅读
- multithreading - 如何将多线程应用于 Bio::SeqIO 翻译代码(Bioperl)?
- github - 使用 GraphQL [Javascript] 从 Github 存储库获取图像
- linux - 通过 CGI 执行 bash 脚本
- autocad - AutoCAD SCR 文件绘制多段线 - 结果不一致
- reactjs - 在 React 16 中无法通过 this.context 访问 contextType
- scala - 如何将该组列表的功能重新制作为简单递归?
- php - 在 WAMP 和 phppgadmin 上集成 postgreSQL
- javascript - 从 AngularJS 1.5 升级到 1.7 会抛出“无法复制!不支持复制 Window 或 Scope 实例”
- html - DevicePixelRatio 似乎突然与 Windows 比例叠加
- python - 获取二维数组中最近的坐标