在python中:如何使用描述符来模拟属性

时间:2017-06-14 09:47:22

标签: python

最近,我正在阅读“学习python”一书。在本书中,它使用描述符来模拟属性如下:

class Property:
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
      self.fget = fget
      self.fset = fset
      self.fdel = fdel # Save unbound methods
      self.__doc__ = doc # or other callables
    def __get__(self, instance, instancetype=None):
      if instance is None:
         return self
      if self.fget is None:
         raise AttributeError("can't get attribute")
      return self.fget(instance) # Pass instance to self
    def __set__(self, instance, value):
      if self.fset is None:
         raise AttributeError("can't set attribute")
      self.fset(instance, value)
    def __delete__(self, instance):
      if self.fdel is None:
          raise AttributeError("can't delete attribute")
      self.fdel(instance)

最后,它说" ...我们必须使用setter和deleter方法扩展我们的Property类,这将保存装饰的访问器函数并返回属性对象(self应该足够)。由于内置属性已经执行此操作,因此我们将在此处省略此扩展的正式编码。" 我的问题是如何实现" setter"装饰者和"删除"装饰师?我不知道

1 个答案:

答案 0 :(得分:1)

Property班级添加方法:

class Property:
    ...
    def setter(self, f):
        self.fset = f
        return self

    def deleter(self, f):
        self.fdel = f
        return self

这些只是简单地获取函数并改变Property的相应属性。然后可以将它们用作例如

class some_thing(object):
    @Property
    def some_property(self):
        ...

    @some_property.setter
    def set_some_property(self, x):
        ...

    @some_property.deleter
    def del_some_property(self):
        ...