自定义一种新类型的元组,对于传入的可迭代对象,只保留其中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-10-02 10:53:34 发布
文章介绍如何在Python中创建一个名为IntTuple的类,该类继承自内置的tuple类型,并在实例化过程中过滤出可迭代对象中的所有大于0的int类型元素。通过重写__new__方法实现元素筛选,保证新实例只包含符合条件的元素。
摘要由CSDN通过智能技术生成