Python class inherits object

后端 未结 6 1038
慢半拍i
慢半拍i 2020-11-21 15:54

Is there any reason for a class declaration to inherit from object?

I just found some code that does this and I can\'t find a good reason why.



        
6条回答
  •  无人共我
    2020-11-21 16:34

    Python 3

    • class MyClass(object): = New-style class
    • class MyClass: = New-style class (implicitly inherits from object)

    Python 2

    • class MyClass(object): = New-style class
    • class MyClass: = OLD-STYLE CLASS

    Explanation:

    When defining base classes in Python 3.x, you’re allowed to drop the object from the definition. However, this can open the door for a seriously hard to track problem…

    Python introduced new-style classes back in Python 2.2, and by now old-style classes are really quite old. Discussion of old-style classes is buried in the 2.x docs, and non-existent in the 3.x docs.

    The problem is, the syntax for old-style classes in Python 2.x is the same as the alternative syntax for new-style classes in Python 3.x. Python 2.x is still very widely used (e.g. GAE, Web2Py), and any code (or coder) unwittingly bringing 3.x-style class definitions into 2.x code is going to end up with some seriously outdated base objects. And because old-style classes aren’t on anyone’s radar, they likely won’t know what hit them.

    So just spell it out the long way and save some 2.x developer the tears.

提交回复
热议问题