我想创建一个带有接受可选参数的装饰器的类属性。通常我会写
def MyProperty(func, optional=None):
def getter():
"""magic goes here"""
return func() if not optional else optional(func())
return property(getter)
class MyClass(object):
@MyProperty
def myFunction(foo):
return foo
MyClass().myFunction(5.)
>>> 5.0
很好,但是当我现在还像这样通过装饰器传递一个函数时:
class MyClass(object):
@MyProperty(int)
def myFunction(foo):
return foo
我现在打电话给
MyClass().myFunction(5)
>>> TypeError: 'property' object is not callable
我希望得到int(5)
作为结果。
写作时
@MyProperty(int)
def myFunction(foo)
...
这意味着调用了MyProperty(int)
,然后以myFunction
作为参数再次调用返回的任何内容。
所以您可以将您的装饰器写成这样:
def MyProperty(optional=None):
def decorator(func):
def getter():
"""unspecified magic goes here"""
return func() if not optional else optional(func())
return getter
return decorator
因此MyProperty(int)
返回一个函数(decorator
),decorator
返回您要修饰的内容。
但是,当您不带参数地调用它时,仍然需要将其命名为@MyProperty()
而不是@MyProperty
,否则会错过展开的阶段。
我不确定您是否使用property
。示例中的两个函数都只是类中的函数。它们没有self
参数或cls
参数,而您是从类本身而不是从实例调用它们的。您的目标尚不清楚。