Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在类装饰器中添加属性?_Python_Decorator_Python Decorators - Fatal编程技术网

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

Python 如何在类装饰器中添加属性?,python,decorator,python-decorators,Python,Decorator,Python Decorators,我正在使用一个decorator自动向Python类添加可序列化性。现在我想知道,我是否可以在decorator中为我想要装饰的类设置一个属性 def序列化(clazz): def内部(实际等级类型): 实际类初始化=实际类初始化类型__ def new_init(self,*args,**kwargs): 酷的东西 #做事 实际初始值(self,*args,**kwargs) 实际类类型。初始化=新初始化 返回实际\u类\u类型 返回内部 使用setattr(实际类类型、属性名称、默认值)

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


def序列化(clazz):
def内部(实际等级类型):
实际类初始化=实际类初始化类型__
def new_init(self,*args,**kwargs):
酷的东西
#做事
实际初始值(self,*args,**kwargs)
实际类类型。初始化=新初始化
返回实际\u类\u类型
返回内部
使用
setattr(实际类类型、属性名称、默认值)

请参见此处的示例:


可能您的装饰器看起来像什么?@chepner为什么需要特定的代码段?它是否依赖于特定的decorator实现?因为如果您的decorator定义了一个类并返回它,那么在该类定义中添加属性应该很简单。如果不是,那么显示代码将使您更清楚地知道您在做什么以及如何修改它。@chepner如果是琐碎的,那么写一个答案。显然,这对我来说并不微不足道。我无法写出答案,因为我不知道您的装饰器是什么样子。您的示例添加了一个属性,而不是属性。然而,被接受的相关问题的答案实际上也回答了我的问题。你想更新你的答案,这样我就可以接受了吗?事实上我想把这个问题标记为重复的,但我认为我没有足够的声誉来做这件事,但也许你可以作为一个创造者来做。更新了答案。这很公平,我至少还是会给你一个投票,因为你给了我正确的方向。雷蒙德·海廷格的回答也是如此。
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