在python中,我需要在我的类,我可能serialize的属性列表,这是麻烦的列出这些在类的顶部。相反,我想用同样的方式@property装饰器使用,这样即东西:蟒蛇装饰添加功能列表上的对象
class MyClass(object):
# I dont like having to do this for example
#__list_of_props_to_serialise__ = ['my_prop',]
@property
@serialise
def my_prop(self):
return "this is my property"
def serialise(self):
return {f: self.getattr(f) for f in self.__list_of_props_to_serialise__}
其中__list_of_props_to_serialise__
被装饰的对象类时建所以更新我不需要的评论在开始时出线。
问题是,当我编写装饰器时,我无法访问类或对象,除非实际调用my_prop
函数,因此我无法添加它。我做错了吗?有没有更好的方法来做到这一点,或者可以做到这一点吗?
如果这样做可以请一些请展示我可以使用的装饰器功能,否则如果有更好的方法,请给出一个例子。
谢谢。
awsome的作品就像一个魅力! ...欢呼 – othane