Python @ property.setter [英] Python @property.setter
问题描述
创建装饰器的基本方法是
The basic way of creating decorators is
def my_decorator(f):
def _f(*args, **kwargs):
# do something using f
pass
return _f
@my_decorator
def f(...):
...
但是那样一来,您就无法定义装饰器,例如 @ property.setter
,因为属性的名称(以及装饰器的名称)每次都不同.
But that way you cannot define decorators like @property.setter
, because the name of the property (and thus the name of the decorator) is different every time.
然后如何定义 @ property.setter
?可以在Python中做类似的事情吗,还是内置功能仅在C(实现)级别可用?
How is it @property.setter
defined then? Is it possible to do something similar in Python, or is it built-in feature available only from C (implementation) level?
推荐答案
您正在寻找的是称为描述符:
class Descriptor(object):
def __get__(self, instance, _type=None):
pass
def __set__(self, obj, value):
pass
您可以自由地实施自己认为合适的事情. property
装饰器只是一个描述符的实例(或多或少),您可以在描述此项的文档中看到它们的实现方式.
You are free to implement things as you see fit. The property
decorator is just an instance of a descriptor (more or less) and you can see how they'd implement it in the documents describing this item.
这是一个例子:
class _Wrapper(object):
def __init__(self, caller, instance):
self.caller = caller
self.instance = instance
def __call__(self, *args, **kwargs):
print "I've been wrapped!"
return self.caller(self.instance, *args, **kwargs)
class Accouncer(object):
def __init__(self, method):
self.method = method
def __get__(self, instance, _type=None):
return _Wrapper(self.method, instance)
def vocal(func):
return Accouncer(func)
class Ha(object):
@vocal
def stuff(self):
return 1
这篇关于Python @ property.setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!