需求:
我们想自定义一种新类型的元组,对于传入的可迭代对象,我们只保留作其中int类型且值大于0的元素,例如:
IntTuple([1,-1,'abc',6,['x','y'],3]) => (1,6,3)
要求IntTuple是内置tuple的子类,如何实现?
思路:
定义IntTuple继承内置tuple,并实现__new__,修改实例化行为(即创建self的行为)
代码:
class IntTuple(tuple):
def __new__(cls,iterable): # cls为类对象的父类,在python中类也是对象
g = (x for x in iterable if isinstance(x,int) and x > 0)
return super(IntTuple,cls).__new__(cls,g) # 返回一个类对象,这个类对象传给下面__init__()方法中的self。
def __init__(self,iterable):
print(self) # 返回类实例对象本身
super(IntTuple,self).__init__()
t = IntTuple([1,-1,'abc',6,['x','y'],3])
print(t)
=================================================================
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)
========================================================================
>>> class A:
... def __new__(cls,*args):
... print('In A.__new__',cls,args)
... return object.__new__(cls)
... def __init__(self,*args):
... print('In A.__init__',args)
...
>>> # a = A(1,2)
>>> a = A.__new__(A,1,2)
In A.__new__ <class '__main__.A'> (1, 2)
>>> a
<__main__.A at 0x7f91ca002908>
>>> A.__init__(a,1,2)
In A.__init__ (1, 2)
>>> list('abc')
['a', 'b', 'c']
>>> l = list.__new__(list,'abc')
>>> l
[]
>>> list.__init__(l,'abc')
>>> l
['a', 'b', 'c']
>>> tuple('abc')
('a', 'b', 'c')
>>> t = tuple.__new__(tuple,'abc')
>>> t
('a', 'b', 'c')
>>> tuple.__init__(t,'abc')
>>> tuple.__init__ is object.__init__
True
>>> list.__init__ is object.__init__
False
>>>