Article From:https://www.cnblogs.com/traditional/p/9219439.html
Task demand:
'''
We want to define a new type of ancestor, for incoming iterated objects.
Only int elements with a value greater than 0 are retained, for example:
IntTuple([1,3,-1,"ab","4",[3,"d"],2]) ==>(1,3,2)
And IntTuple is a subclass of built-in tuple. How to implement it?
'''
class IntTuple(tuple):
    def __init__(self, iterable):
        # Where do we filter before we call the init method of the parent class? Or after?
        # First of all, it is impossible, because the Yuan Dynasty is immutable.
        # Then you can only filter it before
        super(IntTuple, self).__init__(iterable)


# Let's get the parameters first and see the results
t = IntTuple([1, 3, -1, "ab", "4", [3, "d"], 2])
print(t)
'''
TypeError: object.__init__() takes no parameters
'''
# The result is a TypeError, which says object's __init__ does not need parameters.
# This shows that there is no __init__ in tuple, so the __init__ of object is called.
# But if there is no __init__ method in tuple, how does tuple receive parameters?
# So we think of this as a result of the __new__ method
# In fact, when the __new__ method was established, the yuan Zu had been established.
# For lists, [1, 2, and 3] are divided into two steps. First, the __new__ method returns a [], then the __init__ method returns [1,2,3] (adding the value to []).
# But for the ancestors, (1, 2, 3), the __new__ method was returned directly (1, 2, 3), instead of returning () first, and then returned by the __init__ method (1, 2, 3), because tuple had no __init__ at all.Method

 

class IntTuple(tuple):
    # Therefore, to modify, it can only be modified before calling the parent class's __new__ method.
    def __new__(cls, iterable):
        iterable = [x for x in iterable if isinstance(x, int) and x > 0]
        # Note: the __new__ method must have a return value
        # The return value is very fixed, super (defined class, CLS).__new__ (CLS, *args, **kwargs).
        return super(IntTuple, cls).__new__(cls, iterable)


# And then look at the result.
t = IntTuple([1, 3, -1, "ab", "4", [3, "d"], 2])
print(t)

'''
The result of printing is (1, 3, 2)'''
# Mission accomplished

 

Leave a Reply

Your email address will not be published. Required fields are marked *