Actual case :
We want to customize a new type of tuple , For incoming iteratable objects , Keep only one of them int Type and the value is greater than 0 The elements of , for example :IntTuple([1, -1, 'abc', 6, ['x', 'y'], 3]) => (1, 6, 3).
The derived IntTuple The purpose of the new type is to change the instantiation behavior of the built-in tuples , Because the built-in tuple is passed in [1, -1, 'abc', 6, ['x', 'y'], 3] After iteratible object , Every element will go into tuples, which is not what you want at present .
requirement IntTuple It's built in tuple Subclasses of , How to achieve ?
Solution :
Defining classes IntTuple Inherit built in tuple, And implement __new__, Modify the instantiation behavior .
class IntTuple(tuple): # Inherit built in tuple
# Static construction method ,__new__ Will precede __init__ Called
# Realization tuple The filter ,cls For class objects
def __new__(cls, iterable):
# Use the generator to resolve , Filter non int And less than 0 The data of
g = (x for x in iterable if isinstance(x, int) and x > 0)
return super(IntTuple, cls).__new__(cls, g)
t = IntTuple([1, -1, 'abc', 6, ['x', 'y'], 3])
print(t)
# Output results :
(1, 6, 3)