问题
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.
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?
回答1:
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.
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
来源:https://stackoverflow.com/questions/23246400/python-property-setter