返回noncallable的装饰程序是否可以接受其他参数?

2024-04-26 07:46:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我对内置的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),原因很明显。你知道吗


Tags: selfnonefieldgetmakereturnmydef
1条回答
网友
1楼 · 发布于 2024-04-26 07:46:33

你的装潢师不回电话。你的decorator工厂返回一个decorator,它返回一个属性。如果重命名函数,您可能会更好地理解:

def make_decorator(custom_arg_1):
    def decorator(func):
        prop = SerialisableProperty(fget=func)
        prop.extra_field_1 = custom_arg_1
        return prop
    return decorator

当您用make_decorator修饰时,它将用一个参数调用,并且decorator将返回并调用修饰函数。你知道吗

相关问题 更多 >