Python 2.x gotchas and landmines

后端 未结 23 2372
北恋
北恋 2020-11-28 17:47

The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things sp

23条回答
  •  余生分开走
    2020-11-28 18:29

    Unintentionally mixing oldstyle and newstyle classes can cause seemingly mysterious errors.

    Say you have a simple class hierarchy consisting of superclass A and subclass B. When B is instantiated, A's constructor must be called first. The code below correctly does this:

    class A(object):
        def __init__(self):
            self.a = 1
    
    class B(A):
        def __init__(self):
            super(B, self).__init__()
            self.b = 1
    
    b = B()
    

    But if you forget to make A a newstyle class and define it like this:

    class A:
        def __init__(self):
            self.a = 1
    

    you get this traceback:

    Traceback (most recent call last):
      File "AB.py", line 11, in 
        b = B()
      File "AB.py", line 7, in __init__
        super(B, self).__init__()
    TypeError: super() argument 1 must be type, not classobj
    

    Two other questions relating to this issue are 489269 and 770134

提交回复
热议问题