流畅的python

__set__,__setattr__,__getattr__等

2020-03-06  本文已影响0人  洛克黄瓜

__get__,__set__,__delete__

设计描述符descriptor需要使用

# A descriptor
class String:
    def __init__(self, name):
        self.name = name

    def __get__(self, instance, cls):
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, str):
            raise TypeError('Expected a string')
        instance.__dict__[self.name] = value


# A class with a descriptor
class Person:
    name = String('name')

    def __init__(self, name):
        self.name = name


# Extending a descriptor with a property
class SubPerson(Person):
    """这个子类把属性的三个方法都重写了
    """

    @property
    def name(self):
        print('Getting name')
        return super().name

    @name.setter
    def name(self, value):
        print('Setting name to ', value)
        super(SubPerson, SubPerson).name.__set__(self, value)  # __set__是属性的方法

    @name.deleter
    def name(self):
        print('Deleting name')
        super(SubPerson, SubPerson).name__delete__(self)

__getattr__, __getattribute__,getattr

setattr, __setattr__

__getitem__, __setitem__

给对象进行容器化可以对类实现这个函数

class A:
    def __setitem__(self, key, value):
        setattr(self, key, value)

    def __getitem__(self, key):
        return getattr(self, key)
a = A()
a.x = 3
print(a["x"])
----
output:3

如上,可见,通过容器化,使得获取对象的属性有点像访问dict或是list这样的容器

上一篇下一篇

猜你喜欢

热点阅读