Python Objects

About Python Object

In Python, an object is nothing but a variable of an instance of a class.

In Python, a class is like a blueprint while an instance is an implementation of the class with actual values.

Everything in Python is an object, including numbers, strings, functions, and even classes themselves.

Class is the declaration of attributes and methods, while object of the class is the implementation of them.

Multiple objects of a class can be created.

How to create an object of a class in Python

Defining a class
Creating an object
Explanation of the above code
  • Dog("Tom"): This creates an instance of the Dog class by passing argument "Tom" for name attribute.
  • dogObj = Dog("Tom"): When the Dog class instance 'Dog("Tom")' is assigned to the variable 'dogObj', the variable becomes an object of the Dog class. By using 'dogObj', you can access attributes and methods of Dog class as shown below:
Accessing attributes and methods of class
Explanation of the above code
  • print(dogObj.name): This prints the value of 'name' attribute of Dog class by using object of the class (dogObj.name).
  • print(dogObj.bark()): This prints the method named 'bark()' of Dog class by using object of the class (dogObj.bark()).

Please note that a period ('.'), also known as a full stop, is used with a class object to access the attributes and methods of the class.

Examples of Python class and object

Below is the example of Python class and its object to access its attributes and methods.

Example of Python class and object
Output of the above example
Tom
Tom says woof woof!
                                
Explanation of the code
  • dogObj = Dog("Tom"): This creates an instance of the Dog class by passing the argument "Tom" for the name attribute. Here Dog("Tom") is the instance of the Dog class and when it is assigned to the variable 'dogObj', the variable becomes an object of the Dog class. By using 'dogObj', you can access attributes and methods of Dog class.
  • print(dogObj.name): Here the value of 'name' attribute of Dog class is printed by using the object of the class (dogObj.name).
  • print(dogObj.bark()): Here the method named 'bark()' of Dog class is printed by using the object of the class (dogObj.bark()).

Python Compiler For Live Practice

Practice the above Python code in the following Python Editor. Create more Python class and its object to access its attributes and methods in the following Python code editor and click Execute button to check the output. Output will be displayed in Python Code Output section.

Python logo Python Editor
Python Code Output