TypeError in Python single inheritance with “super” attribute

前端 未结 1 2048
一向
一向 2021-02-07 20:15

I never expected the inheritance of Python 2.7 is so anti-human. Why the following code give me a TypeError?

>>> class P:
...     def _         


        
1条回答
  •  孤城傲影
    2021-02-07 20:47

    There are two responses possible for your question, according to the version of Python you're using.

    Python 2.x

    super has to be called like this (example for the doc):

    class C(B):
        def method(self, arg):
            super(C, self).method(arg)
    

    In your code, that would be:

    >>> class P(object):    # <- super works only with new-class style
    ...     def __init__(self, argp):
    ...         self.pstr=argp
    ... 
    >>> class C(P):
    ...     def __init__(self, argp, argc):
    ...         super(C, self).__init__(argp)
    ...         self.cstr=argc
    

    You also don't have to pass self in argument in this case.

    Python 3.x

    In Python 3.x, the super method has been improved: you can use it without any parameters (both are optional now). This solution can work too, but with Python 3 and greater only:

    >>> class C(P):
    ...     def __init__(self, argp, argc):
    ...         super().__init__(argp)
    ...         self.cstr=argc
    

    0 讨论(0)
提交回复
热议问题