python - Python - 如何以编程方式添加属性访问器
问题描述
class A:
def __init__(self, *args, **kwargs):
for item in ["itemA", "itemB"]:
setattr(self, item, property(lambda : self.__get_method(item)))
def __get_method(self, item):
# do some stuff and return result
# this is pretty complex method which requires db lookups etc.
return result
我试图想出上面的例子来在初始化期间创建类属性。项目列表将来会变得更大,并且不想@property
每次添加新条目时都添加。
但是无法从属性中获取结果,而是从对象位置获取结果。
a = A()
a.itemA # returns <property at 0x113a41590>
最初是这样的,并意识到这可能会更好。
class A:
@property
def itemA(self):
return self.__get_method("itemA")
@property
def itemX(self):
...
# and so on
我如何仅通过向items
列表中添加新条目来添加新属性,并且类本身将为它创建访问器?
解决方案
除了@juanpa.arrivillaga 评论。你也可以实现__getattr__
方法
例如:
class A:
def __getattr__(self, name):
#make everybody happy
推荐阅读
- post - 将 ESP32 CAM 拍摄的图像发布到 Clarifai 不起作用
- python - 如何链接/或组合我的三个 Django 模型以更好地最大化关系和效率
- batch-file - 批处理:如何从文本文件的目录路径中排除带有扩展名的文件名?
- python - 有人能告诉我为什么我的计算器应用程序上的按钮是空白的吗?
- java - 在java中将字符串转换为数组的问题
- gfortran - Windows子系统ubuntu中gfortran中对“dgemm_”的未定义引用
- javascript - 如何通过使用 reducer 和处理事件来更新事件数组中的事件?
- browser-cache - 如何强制客户端不缓存 svelte/rollup bundle.js?
- azure-cosmosdb - 检索不同的属性
- c - C 套接字,jpeg 图像无法正确显示