Kara Kara - 1 year ago 144
Python Question

Should all Python classes extend object?

I have found that both of the following work:

class Foo():
def a(self):
print "hello"

class Foo(object):
def a(self):
print "hello"

Should all Python classes extend object? Are there any potential problems with not extending object?

Answer Source

In Python 2, not inheriting from object will create an old-style class, which, amongst other effects, causes type to give different results:

>>> class Foo: pass
>>> type(Foo())
<type 'instance'>


>>> class Bar(object): pass
>>> type(Bar())
<class '__main__.Bar'>

Also the rules for multiple inheritance are different in ways that I won't even try to summarize here. All good documentation that I've seen about MI describes new-style classes.

Finally, old-style classes have disappeared in Python 3, and inheritance from object has become implicit. So, always prefer new style classes unless you need backward compat with old software.