我对内置的property
类(称之为SpecialProperty
)进行了子类化,以便向其添加更多字段:
class SpecialProperty(property):
extra_field_1 = None
extra_field_2 = None
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
super().__init__(fget, fset, fdel, doc)
def make_special_property(func):
prop = SerialisableProperty(fget=func)
return prop
我能够以与内置property()
装饰器相同的方式使用它:
@my_module.make_special_property
def get_my_property(self): return self._my_property
现在我想进一步专门化我的SpecialProperty
实例,用任意值填充我添加到类中的一个额外字段。你知道吗
在Python中,是否可以编写一个decorator来返回一个属性,同时接受额外的参数?
我想通过装饰,因为这是地方和时间的信息是最相关的,但我发现自己卡住了。我怀疑这属于decorators的范畴,其参数已经被很好地记录了(Decorators with arguments? (Stack Overflow),或Python Decorators II: Decorator Arguments (artima.com)仅引用几个源代码),但是我发现自己无法将相同的模式应用到我的案例中。你知道吗
我是这样写的:
@my_module.make_special_property("example string")
def get_my_property(self): return self._my_property
在声明get_my_property
的类上:
>>> DeclaringClass.my_property
<SpecialProperty object at 0x...>
>>> DeclaringClass.my_property.extra_field_1
'example string'
由于我正在制作properties
,修饰的类成员应该与SpecialProperty
的实例交换,因此不应该再是可调用的——因此,我无法应用“嵌套包装器”模式来允许带有参数的修饰器。你知道吗
非工作示例:
def make_special_property(custom_arg_1):
def wrapper(func):
prop = SerialisableProperty(fget=func)
prop.extra_field_1 = custom_arg_1
return prop
return wrapper # this returns a callable (function)
我不应该在这里返回一个callable,如果我想要一个属性,我应该返回一个SpecialProperty
实例,但是我不能调用return wrapper(func)
,原因很明显。你知道吗
你的装潢师不回电话。你的decorator工厂返回一个decorator,它返回一个属性。如果重命名函数,您可能会更好地理解:
当您用
make_decorator
修饰时,它将用一个参数调用,并且decorator
将返回并调用修饰函数。你知道吗相关问题 更多 >
编程相关推荐