AppDividend
Latest Code Tutorials

Python Object Example | Python object() Method

0

Python object function returns the empty object. We cannot add new properties or methods to this object.
This object is the base for all the classes, and it holds the built-in properties and methods, which are the default for all classes. Python object() function returns a featureless object.

Python Object Example

In python, each variable to which we assign a value/container is treated as an object.

The object in itself is a class.

Syntax

object()

This method does not have any parameters.

The object() method returns a featureless class which acts as a base for all the objects.

See the following example.

# app.py

# Declaring the object of class object
obj1 = object()
obj2 = object()

# Printing the type
print("Type of the object class object is : ", type(obj1))

# Printing its attribute
print(dir(obj2))

# Now check if obj1 and obj2 are equal or not

print(str(obj1 == obj2))

# Now we will try to add an attribute to 0bj2
# Lets see what happens

obj2.address = "India"

See the output.

('Type of the object class object is : ', <type 'object'>)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
False
Traceback (most recent call last):
  File "object.py", line 18, in <module>
	obj2.address="India"
AttributeError: 'object' object has no attribute 'address'

In the program, we have declared two objects, and then we are printing its type and attributes.

We used built-in functions type() and dir() to get type and all attributes of the object, respectively.

The object doesn’t have __dict__ as suggested by the output. Hence, you can’t assign arbitrary attributes to the instances of this class.

If we assign any property to the object, then it will give us an AttributeError: ‘object’ object has no attribute

#Properties of object

  1. The object always acts as a base class for all the objects that we create.
  2. Objects of object class cannot add a new attribute to it.
  3. These objects are uniquely made, and they never return true if we compare which another object.

Atlast, Python object() method example is over.

Recommended Posts

Python memoryview()

Python issublclass()

Python open()

Python ord()

Python hex()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.