Python的-描述器Descriptor-例子

44次阅读

共计 324 个字符,预计需要花费 1 分钟才能阅读完成。

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)

正文完
 0