[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.

你可能感兴趣的:(python)