簡體   English   中英

Python @ property.setter

[英]Python @property.setter

創建裝飾器的基本方法是

def my_decorator(f):
    def _f(*args, **kwargs):
        # do something using f
        pass
    return _f

@my_decorator
def f(...):
    ...

但是那樣一來,您就無法定義@property.setter類的裝飾器,因為@property.setter的名稱(以及裝飾器的名稱)每次都不同。

那么@property.setter是如何定義的? 是否可以在Python中做類似的事情,還是僅在C(實現)級別提供了內置功能?

您正在尋找的是稱為描述符的東西:

 class Descriptor(object):
   def __get__(self, instance, _type=None):
     pass
   def __set__(self, obj, value):
     pass

您可以自由地執行自己認為合適的事情。 property裝飾器只是一個描述符的實例(或多或少),您可以在描述該項目的文檔中看到它們的實現方式。

這是一個例子:

  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM