乐趣区

Python的-描述器Descriptor-例子

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)
退出移动版