【问题标题】:How can I add a property inside a class decorator?如何在类装饰器中添加属性?
【发布时间】:2019-11-02 04:03:08
【问题描述】:

我正在使用装饰器为我的 Python 类自动添加可序列化性。现在我想知道,我是否也可以为我想在装饰器中装饰的类设置一个属性。


def serialize(clazz):
  def inner(actual_class_type):
    actual_init = actual_class_type.__init__

    def new_init(self, *args, **kwargs):
      cool_thing = clazz()

      # do stuff

      actual_init(self, *args, **kwargs)

    actual_class_type.__init__ = new_init

    return actual_class_type

  return inner    

【问题讨论】:

  • 可能吗?你的装饰器是什么样的?
  • @chepner 为什么需要特定的代码 sn-p?是否依赖于具体的装饰器实现?
  • 因为如果您的装饰器定义了一个类并返回它,那么在该类定义中添加一个属性应该是微不足道的。如果没有,那么显示您的代码将使您做什么以及如何修改它更清楚。
  • @chepner 如果它是微不足道的,那么写一个答案。显然这对我来说不是微不足道的。
  • 我写不出答案,因为我不知道你的装饰器长什么样。

标签: python decorator python-decorators


【解决方案1】:

使用setattr(actual_class_type, attribute_name, default_value)

请参见此处的示例: How can I add properties to a class using a decorator that takes a list of names as argument?

def serialize(clazz):
  def inner(actual_class_type):
    actual_init = actual_class_type.__init__

    def new_init(self, *args, **kwargs):
      cool_thing = clazz()

      # do stuff

      actual_init(self, *args, **kwargs)

    actual_class_type.__init__ = new_init

    prop_name = "my_prop"
    def getAttr(self):
      return getattr(self, "_" + prop_name)
    def setAttr(self, value):
      setattr(self, "_" + prop_name, value)
    prop = property(getAttr, setAttr)
    setattr(cls, prop_name, prop)
    setattr(cls, "_" + prop_name, None) # Default value for that property

    return actual_class_type

  return inner   

【讨论】:

  • 您的示例添加了一个属性,而不是一个属性。然而,链接的问题接受的答案实际上也回答了我的问题。你想更新你的答案,以便我接受吗?
  • 实际上我想将此问题标记为重复,但我认为我没有足够的声誉来做到这一点,但也许你可以作为创作者做到这一点。更新了答案。
  • 那是公平的,我至少仍然会给你一个赞成票,因为你给我指明了正确的方向。 Raymond Hettinger 的回答也不少。
猜你喜欢
  • 2017-11-19
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多