自定义一种新类型的元组,对于传入的可迭代对象,只保留其中int类型且大于0的元素,例如:
IntTuple([1,-1,'abc',6,['x','y'],3]) => (1,6,3)
要求IntTuple是内置tuple的子类
# 标准继承框架
class IntTuple(tuple): # 继承内置tuple
def __init__(self, iterable): # 创建构造器
# before
super(IntTuple, self).__init__(iterable) # 调用了父类构造器方法
# after
t = IntTuple([1,-1,'abc',6,['x','y'],3])
print t
# 当前IntTuple和内置tuple完全一致
class IntTuple(tuple): # 继承内置tuple
def __init__(self, iterable): # 创建构造器
# before
super(IntTuple, self).__init__(iterable) # 调用了父类构造器方法
# after 在之后无法过滤,self是tuple的一个实例,tuple是一个不可变对象,无法在self中删除
t = IntTuple([1,-1,'abc',6,['x','y'],3])
print t
class IntTuple(tuple): # 继承内置tuple
def __init__(self, iterable): # 创建构造器
# before 对iterable处理
print self # 已经对tuple实例化
super(IntTuple, self).__init__((1,6,3)) # 调用了父类构造器方法
# after
t = IntTuple([1,-1,'abc',6,['x','y'],3])
print t # [1,-1,'abc',6,['x','y'],3] ----说明before处理也不行
#
定义类IntTuple继承内置tuple,并实现__new__,修改实例化行为
class IntTuple(tuple): # 继承内置tuple
def __new__(cls, iterable): # 是一个静态方法,当创建IntTuple实例时,__new__先于__init__调用。第一个参数是个类对象,Python中一切皆对象,创建IntTuple对象,那么class IntTuple这个类就会传入进来;其他参数需要几个定义几个,和init一致
g = (x for x in iterable if isinstance(x,int) and x > 0)
return super(IntTuple,cls).__new__(cls,g) # 过滤后的iterable;返回一个过滤后创建的实例到init中的self
def __init__(self, iterable): # 创建构造器
# before
super(IntTuple, self).__init__(iterable) # 调用了父类构造器方法
# after
t = IntTuple([1,-1,'abc',6,['x','y'],3])
print t
6.1【类与对象】如何派生内置不可变类型并修改其实例化行为?
最新推荐文章于 2024-06-11 18:07:33 发布