【问题标题】:Python - how to add property accessors programmaticallyPython - 如何以编程方式添加属性访问器
【发布时间】:2020-09-18 00:15:57
【问题描述】:
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 列表添加新条目来添加新属性,并且类本身将为它创建访问器?

【问题讨论】:

  • 属性必须属于 才能工作。所以如果你真的想这样做,就在你的类定义之后,做类似ffor item in ["itemA", "itemB"]: setattr(A, item, property((lambda item: lambda self: self._A__get_method(item))(item)))

标签: python python-3.x properties accessor


【解决方案1】:

@juanpa.arrivillaga 评论的补充。 你也可以实现__getattr__方法

例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2022-01-16
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 2019-05-11
    • 2021-01-30
    相关资源
    最近更新 更多