Python: How do I make a subclass from a superclass?

后端 未结 11 1837
日久生厌
日久生厌 2020-11-29 19:01

In Python, how do you make a subclass from a superclass?

11条回答
  •  感情败类
    2020-11-29 19:15

    In the answers above, the super is initialized without any (keyword) arguments. Often, however, you would like to do that, as well as pass on some 'custom' arguments of your own. Here is an example which illustrates this use case:

    class SortedList(list):
        def __init__(self, *args, reverse=False, **kwargs):
            super().__init__(*args, **kwargs)       # Initialize the super class
            self.reverse = reverse
            self.sort(reverse=self.reverse)         # Do additional things with the custom keyword arguments
    

    This is a subclass of list which, when initialized, immediately sorts itself in the direction specified by the reverse keyword argument, as the following tests illustrate:

    import pytest
    
    def test_1():
        assert SortedList([5, 2, 3]) == [2, 3, 5]
    
    def test_2():
        SortedList([5, 2, 3], reverse=True) == [5, 3, 2]
    
    def test_3():
        with pytest.raises(TypeError):
            sorted_list = SortedList([5, 2, 3], True)   # This doesn't work because 'reverse' must be passed as a keyword argument
    
    if __name__ == "__main__":
        pytest.main([__file__])
    

    Thanks to the passing on of *args to super, the list can be initialized and populated with items instead of only being empty. (Note that reverse is a keyword-only argument in accordance with PEP 3102).

提交回复
热议问题