Python的 描述器(Descriptor) 例子

RobinTang
def Itemgetter(x):
    def get(s):
        return s[x]
    return get
    
class Property(object):  # 必须是新式类
    def __init__(self, fget):
        self.fget = fget
    def __get__(self, obj, objtype):
        return self.fget(obj)
    def __set__(self, instance, value):
        pass
    def __delete__(self, instance):
        pass

class Test(tuple):
    x = Property(Itemgetter(0))
    y = Property(Itemgetter(1))


a = Test((1, 2))
print(a.x, a.y)
阅读 955

3.9k 声望
36 粉丝
0 条评论
3.9k 声望
36 粉丝
文章目录
宣传栏