美文网首页
python(Class1)

python(Class1)

作者: OldSix1987 | 来源:发表于2016-09-11 10:14 被阅读10次

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





class IntTuple(tuple):
    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)  (1, 6, 3)
        super(IntTuple, self).__init__()
        # after


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


'''

1. 判断一个变量是否是int类型:isinstance(x, int)
2. tuple生成器:g = (x for x in iterable if isinstance(x, int) and x > 0)

'''

相关文章

网友评论

      本文标题:python(Class1)

      本文链接:https://www.haomeiwen.com/subject/rhbyettx.html