如何在类装饰器中添加属性?

时间:2019-06-19 12:05:07

标签: python decorator python-decorators

我正在使用装饰器向我的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    

1 个答案:

答案 0 :(得分: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