In the above answers, super initialized with no arguments (keyword). Often, however, you would like to do this, as well as pass some of your own “own” arguments. Here is an example illustrating this use case:
class SortedList(list): def __init__(self, *args, reverse=False, **kwargs): super().__init__(*args, **kwargs)
This is a subclass of list , which, upon initialization, immediately sorts itself in the direction indicated by the argument to the reverse keyword, as the following tests show:
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)
Thanks to the transfer from *args to super list can be initialized and filled with elements, and not just empty. (Note that reverse is a keyword-only argument according to PEP 3102 ).
Kurt Peek Nov 21 '17 at 1:46 on 2017-11-21 01:46
source share