[英]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(...):
...
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
类的装饰器,因为@property.setter
的名称(以及装饰器的名称)每次都不同。
How is it @property.setter
defined then? 那么
@property.setter
是如何定义的? Is it possible to do something similar in Python, or is it built-in feature available only from C (implementation) level? 是否可以在Python中做类似的事情,还是仅在C(实现)级别提供了内置功能?
What you are looking for is something called a descriptor : 您正在寻找的是称为描述符的东西:
class Descriptor(object):
def __get__(self, instance, _type=None):
pass
def __set__(self, obj, value):
pass
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. property
装饰器只是一个描述符的实例(或多或少),您可以在描述该项目的文档中看到它们的实现方式。
Here's an example: 这是一个例子:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.