6.1【类与对象】如何派生内置不可变类型并修改其实例化行为?

自定义一种新类型的元组,对于传入的可迭代对象,只保留其中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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值