Python @property.setter

亡梦爱人 提交于 2021-01-27 22:14:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!