11

If I define a class in Python such as:

class AClass:
   __slots__ = ['a', 'b', 'c']

Which class does it inherit from? It doesn't seem to inherit from object.

Verhogen
  • 27,221
  • 34
  • 90
  • 109
  • All of the answers regarding `object` and old vs new classes are right, but why do you ask? Is there a practical reason or is it just a philosophical/language-design question? (Because in most cases, it doesn't matter!) – Andrew Jaffe Feb 05 '11 at 10:16
  • What version of Python? Python 2 and Python 3 do this differently. – S.Lott Feb 05 '11 at 14:15
  • I think I was trying to extend this class, but it wouldn't let me extend it until I made it inherit from Object. – Verhogen Feb 18 '11 at 06:18

4 Answers4

15

If you define a class and don't declare any specific parent, the class becomes a "classic class", which behaves a bit differently than "new-style classes" inherited from object. See here for more details: http://docs.python.org/release/2.5.2/ref/node33.html

Classic classes don't have a common root, so essentially, your AClass doesn't inherit from any class.

Note that this is specific to Python versions before 3.0. In Python 3, all classes are new-style classes and inherit implicitly from object, if no other parent is declared.

shang
  • 24,642
  • 3
  • 58
  • 86
10

Try the following code snippet in Python 2.7 and Python 3.1

class AClass:
   __slots__ = ['a', 'b', 'c']
print(type(AClass))
print(issubclass(AClass,object))
print(isinstance(AClass,type))

In Python 2.7, you will get:

<type 'classobj'>
False
False

And Python 3.1 you will get.

<class type>
True
True

And that explains it all. It is old style class in Python 2, unless you subclass it from object. Only in Python3, it will be treated like a new style class by default.

Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
2

In Python 2.x or older, your example AClass is an "old-style" class.

A "new-style" class has a defined inheritance and must inherit from object or some other class.

What is the difference between old style and new style classes in Python?

EDIT: Wow, I didn't think it was possible to use the old-style syntax in Python 3.x. But I just tried it and that syntax still works. But you get a new-style class.

Community
  • 1
  • 1
steveha
  • 74,789
  • 21
  • 92
  • 117
2

Let's try it out.

>>> class AClass:
...     pass
... 
>>> AClass.__bases__, type(AClass)
( (), <type 'classobj'> )                # inherits from nothing

>>> class AClass(object):                # new style inherits from object
...     pass
... 
>>> AClass.__bases__, type(AClass)
( (<type 'object'>,), <type 'type'> )

Read an introduction to the new style classes in the links given in other answers.

user225312
  • 126,773
  • 69
  • 172
  • 181