Python class inherits object

后端 未结 6 1040
慢半拍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:27

    History from Learn Python the Hard Way:

    Python's original rendition of a class was broken in many serious ways. By the time this fault was recognized it was already too late, and they had to support it. In order to fix the problem, they needed some "new class" style so that the "old classes" would keep working but you can use the new more correct version.

    They decided that they would use a word "object", lowercased, to be the "class" that you inherit from to make a class. It is confusing, but a class inherits from the class named "object" to make a class but it's not an object really its a class, but don't forget to inherit from object.

    Also just to let you know what the difference between new-style classes and old-style classes is, it's that new-style classes always inherit from object class or from another class that inherited from object:

    class NewStyle(object):
        pass
    

    Another example is:

    class AnotherExampleOfNewStyle(NewStyle):
        pass
    

    While an old-style base class looks like this:

    class OldStyle():
        pass
    

    And an old-style child class looks like this:

    class OldStyleSubclass(OldStyle):
        pass
    

    You can see that an Old Style base class doesn't inherit from any other class, however, Old Style classes can, of course, inherit from one another. Inheriting from object guarantees that certain functionality is available in every Python class. New style classes were introduced in Python 2.2

提交回复
热议问题