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

问题举例

自定义一种新类型的元组,对传入的可迭代对象,我们只保留

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

其中int类型且值大于0的元素,例如

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

如何继承内置tuple实现IntTuple?

 

分析

对象的初始化有两个部分:__new__和__init__方法,

对于tuple而言,它并没有__init__方法,直接在__new__中初始化

 

解决思路

继承内置tuple,并实现__new__,在其中修改实例化行为

 

代码

class IntTuple(tuple):
    def __new__(cls, iterable):
        # 过滤iterable
        f_it = (e for e in iterable if isinstance(e, int) and e > 0)
        return super().__new__(cls, f_it)

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

 

参考资料:python3实用编程技巧进阶

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄