Python Reference ยท Built-in Functions
Python object class
Reference for Python's object: the base class of all classes, what it provides, creating sentinel objects, __slots__ and why every class inherits from it.
object is the root of Python's class hierarchy. Every class, built-in or your own, inherits from it, directly or indirectly. It supplies the default behavior everything shares: a default __repr__, __eq__ based on identity, __hash__, __init__, __new__, __setattr__, __getattribute__ and more.
Calling object() creates a bare instance with no attributes and no way to add any. That sounds useless, but it is a perfect sentinel: a unique value that can never equal anything else.
marker = object() marker == object() # False, each instance is unique isinstance(5, object) # True, everything is an object
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
object()
| Name | Description |
|---|---|
| (none) | object() takes no arguments. Subclasses define their own __init__ parameters. |
Return value: a new, featureless instance.
Raises: TypeError if you pass arguments to object() itself.
Usage notes
- Every class inherits from
objectin Python 3, even without writing it.class A:andclass A(object):are identical, so the explicit form is only a Python 2 habit. - Default equality is identity. Two instances are equal only if they are the same object, until a class defines
__eq__. If you define__eq__, also think about__hash__. - Default
__repr__looks like<__main__.Dog object at 0x...>. Define__repr__for something more useful. - Plain
object()instances have no__dict__, so you cannot attach attributes. Instances of your own classes can, unless you declare__slots__. - Sentinels from
object()solve "was an argument passed?" whenNoneis a valid value. Compare them withis. - Method resolution order (MRO).
objectis always the last entry of__mro__, sosuper()chains end there. object.__init__accepts no extra arguments, which is why cooperative multiple inheritance must stop passing arguments before reaching it.- It is not a type annotation for "anything useful".
x: objectallows any value but lets you do almost nothing with it; use a specific type, a protocol ortyping.Any.