[python] __get__ of descriptor

class Property:
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        self.__doc__ = doc

    def __get__(self, instance, owner=None):
        if instance is None:
            print("Access through class")
            return self
        if self.fget is None:
            raise AttributeError("fetch error")
        return self.fget(instance)

    def __set__(self, instance, value):
        if self.fset is None:
            raise AttributeError("set error")
        self.fset(instance, value)

    def __delete__(self, instance):
        if self.fdel is None:
            raise AttributeError("delete error")
        self.fdel(instance)

class Client0:
    def __init__(self, name):
        self._name = name
    def getName(self):
        print("getName...")
        return self._name
    def setName(self, value):
        print("setName...")
        self._name = value
    name = Property(getName, setName)

if __name__ == "__main__":
    i = Client0('alice')
    print(i.name)
    i.name = 'bob'
    print(i.name)
    print(Client0.name)

output:

getName...
alice
setName...
getName...
bob
Access through class
<__main__.Property object at 0x7fa94838aac8>

so, why need owner, which is the class of instance, in __get__(self, instance, owner=None)?
refer to:

https://stackoverflow.com/questions/8719585/why-does-a-python-descriptor-get-method-accept-the-owner-class-as-an-arg
owner is used when the attribute is accessed from the class instead of an instance of the class, in which case instance will be None.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值