Python object() Function



The Python object() function is a built-in function that returns a new object. This object is the base for all classes in Python, and it lacks features and attributes. Note that adding any new properties or methods to this object is not possible.

When we call the object() function, it creates an instance of the base object class, which is by default empty. In Python, every class we create implicitly inherits from this class, which means any instance of any class is also an instance of the object class.

Syntax

Following is the syntax of the Python object() function −

object()

Parameters

The Python object() function does not accept any parameters.

Return Value

The Python object() function returns a new featureless object.

Examples

In this section, we will see some examples of object() function −

Example 1

In the code below an instance of the object class is instantiated. Then, we check for the type of this object using the type() function.

newObject = object()
checker = type(newObject)
print("The type of object of object class:", checker)

Following is an output of the above code −

The type of object of object class: <class 'object'>

Example 2

The following example shows the basic usage of Python object() function where we create a new, featureless object instance which has no class methods or attributes.

newObject = object()
print(newObject)

When we run above program, it produces following result −

<object object at 0x780e80404510>

Example 3

The object() function can be used to check if a particular class is a direct or indirect subclass of another. In the code below, we are checking if the class "newClass" is a subclass of "object". Since all classes in Python inherit from object class, the code will return True.

class newClass:
   pass

checker = issubclass(newClass, object)
print("Is the newClass a subclass of object:", checker)

Following is an output of the above code −

Is the newClass a subclass of object: True

Example 4

The object() function comes at the end of Method Resolution Order chain in Python classes. To demonstrate the same we are using the "mro()" method which lists the order in which methods are resolved.

class newClass:
   pass

class newChildClass(newClass):
   pass

print("The order of method resolution:")
print(newChildClass.mro())

Output of the above code is as follows −

The order of method resolution:
[<class '__main__.newChildClass'>, <class '__main__.newClass'>, <class 'object'>]
python_built_in_functions.htm
Advertisements