Python 如何派生内置不可变类型并修改其实例化行为

Jackey Python 1,764 次浏览 没有评论
# 如何派生内置不可变类型并修改其实例化行为
class IntTuple(tuple):
    # 实现 __new__ 方法
    def __new__(cls, iterable):
        g = (x for x in iterable if isinstance(x, int) and x > 0)
        return super(IntTuple, cls).__new__(cls, g)

    def __init__(self, iterable):
        # before
        print(self)
        super(IntTuple, self).__init__()
        # after


t = IntTuple([1, -1, 'abc', 6, ['x', 'y'], 3])
print(t)

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go