How to create object of a Python class?

In this tutorial you will learn about how to create a object of a Python class. To create an object of a Python class, you first need to define the class and then instantiate it. Creating objects involves defining classes as blueprints for objects and then instantiating those classes to create individual instances. A class serves as template, encapsulating both attributes and methods that objects will possess. Almost everything in Python is an object, with its properties and methods.

Defining a Class:

Define the blueprint of your object by creating a class. Classes in Python are defined using the classes keyword followed by the class name.

Instantiate the Class:

Once the class is defined, you can create objects (also known as instances) of that class by calling the class name followed by parentheses.

Syntax:

#To define a class:

class ClassName:

#To create an object of this class:

object_name= ClassName()

For example:

class Car:
   name = ""
   gear = 0
car = Car()
car1.gear = 5
car1.name = "Kia"
print(f"Name:{car1.name}, Gears: {car1.gear} ")

Output:

Name: Kia, Gears: 5

In the above example, we have defined the class name Car with two attributes: name and gear.
we have also created an object car1 of the class Car.
Finally, we have accessed and modified the properties of an object using the (.) notation.

For Creating Multiple Objects of Python Class:

#We can create multiple objects of a Python class

For example:

class Dog:
    attr1 = "Dusky"
    attr2 = "Dog"
    def fun(self):
        print("I'm a", self.attr1)
        print("I'm a", self.attr2)
Rodger = Dog()
print(Rodger.attr1)
Rodger.fun()

Output:

Dusky
I'm a Dusky
I'm a Dog

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top