开发者

Python 'object' type and inheritance

开发者 https://www.devze.com 2022-12-08 06:00 出处:网络
In Python I can define a class \'foo\' in the following ways: class foo: pass or class foo(object): pass What is the difference?I have tried to use the function issubclass(foo, object) to see if

In Python I can define a class 'foo' in the following ways:

class foo:
    pass

or

class foo(object):
    pass

What is the difference? I have tried to use the function issubclass(foo, object) to see if it returns True for both class de开发者_JAVA技巧finitions. It does not.

IDLE 2.6.3      
>>> class foo:
        pass

>>> issubclass(foo, object)
False
>>> class foo(object):
        pass

>>> issubclass(foo, object)
True

Thanks.


Inheriting from object makes a class a "new-style class". There is a discussion of old-style vs. new-style here: What is the difference between old style and new style classes in Python?

As @CrazyJugglerDrummer commented below, in Python 3 all classes are "new-style" classes. In Python 3, the following two declarations are exactly equivalent:

class A(object):
    pass

class A:
    pass


The first creates an "old-style" class, which are deprecated and have been removed in Python 3. You should not use it in Python 2.x. See the documentation for the Python data model.


Old style and new style objects... they have sightly different behaviours, for example in the constructors, or in the method resolution order in multiple inheritance.

0

精彩评论

暂无评论...
验证码 换一张
取 消