55

When I create a module with its sole content:

class Classname(randomobject):
    pass

And I try to run the .py file of the module the interpreter says that randomobject is not defined.

But when I do:

class Classname(object):
    pass

The module runs just fine. So if object is not a keyword, then what is it?

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
Bentley4
  • 10,678
  • 25
  • 83
  • 134
  • Here's another question which addresses the Python `object` identifier: [python class inherits object](http://stackoverflow.com/q/4015417/404469). – gary Jan 03 '13 at 22:16
  • 5
    For the record, http://stackoverflow.com/q/4015417/404469 is not a duplicate. It's about the mechanism of inheritance; this question is about, and has multiple answers about, the syntactic structure of what's going on. – Marcin Jun 18 '17 at 16:54

4 Answers4

32

object is a (global) variable. By default it is bound to a built-in class which is the root of the type hierarchy.

(This leads to the interesting property that you can take any built-in type, and use the __bases__ property to reach the type called object).

Everything built-in that isn't a keyword or operator is an identifier.

Marcin
  • 48,559
  • 18
  • 128
  • 201
  • Thank you. I assume you can't view the code what is being assigned to this global variable? – Bentley4 Apr 06 '12 at 16:15
  • @Bentley4 I don't know what you mean. – Marcin Apr 06 '12 at 16:25
  • I'm sorry. In /usr/lib/python2.7 you can find the standard python modules. By opening the python files yourself you can see variable assignments, bodies of the classes and functions etc. of the modules that you can't see by using the help function. Is there any way to access the __builtin__ module and look at the object variable in that module? – Bentley4 Apr 06 '12 at 17:15
  • 1
    @Bentley4 I've never tried. Consider grepping for it; if not, you'll have to find it in the C source. – Marcin Apr 06 '12 at 17:16
17

The following three class declarations are identical in Python 3

class Classname(object):
    pass

class Classname():
    pass

class Classname:
    pass

Well, there will be minor differences, but not fundamentally important since the object class is the base for all.

If you plan to write Python agnostic code (Python2 and Python3 agnostic) you may use the first declaration.

prosti
  • 42,291
  • 14
  • 186
  • 151
8

object is an identifier that refers to a builtin type.

Unlike many other languages, there are no primitive types in Python. Everything is an object, including all data types.

I'm not sure why you expected inheriting from randomobject to work.

Taymon
  • 24,950
  • 9
  • 62
  • 84
7

object is the base class from which you inherit when creating a new-style class in Python 2.

Kien Truong
  • 11,179
  • 2
  • 30
  • 36