案例:
我们想自定义一种新类型的元组,对于传入的可迭代对象,我们只保留作其中int类型且值大于0的元素,例如:
intTuple([1,-1,'abc',6,['x','y'],3)b => (1,6,3)
要求intTuple是内置tuple的子类,如何实现?
重写__new__类方法,new方法是对参数进行实例操作,在此之间,对实例参数进行预操作,修改实例化行为
class IntTuple(tuple): #自定义一个类,继承tuple元组类
def __new__(cls, iterable): #new方法是在init方法之前进行调用的方法,作用是为对象分配内存空间并返回对象的引用
g = (x for x in iterable if isinstance(x,int) and x > 0) # 定义一个生成式,写条件过滤掉不符合的元素
return super(IntTuple, cls).__new__(cls, g) #super方法继承本类,cls代表当前intTuple类本身,把参数变成生成式,返回给这个类本身的__new__方法
def __init__(self,iterable): #此时iterable引用了被__new__类方法修改过的实例参数
pass
if __name__ == '__main__':
t = IntTuple([1,-1,'abc',6,['x','y'],3])
print(t) #打印(1,6,3)