首页 > 解决方案 > 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列表中添加新条目来添加新属性,并且类本身将为它创建访问器?

标签: pythonpython-3.xpropertiesaccessor

解决方案


除了@juanpa.arrivillaga 评论。你也可以实现__getattr__方法

例如:

class A:
    def __getattr__(self, name):
        #make everybody happy
        

推荐阅读