A python is an object-oriented programming language. Almost everything in Python is considered as an object. An object has its own properties(attributes) and behavior(methods).
A class is a blueprint of the objects or can be termed as object constructor for creating objects.
One class can have many objects and value of properties for different objects can be different.
Let’s take the example of car as an object. Its properties will include its color, company name, year of manufacture , price , mileage etc. The behavior of the car will include the functions it can perform, this will include increase speed, decrease speed, apply brakes etc. Object basically related everything with real life objects. Everything we find around us in real life has some properties and some functions.
Different objects belonging to same class can have different properties. For example, Person(Human) can be treated as a class which has properties such as name, age,gender etc. Every individual can be treated as an object of the class human or Person. Each individual will have different values of the properties of class Person.Everyone will have different names, age and gender.
An object is also called an instance of a class. Thus, the process of creating object of a class is known as instantiation.
As the function in Python is defined using the keyword ‘def’. The keyword ‘class’ is used to define a class in Python. Since the class is a blueprint of the object, all the common attributes and methods will be declared and defined in the class. Different objects which are created from the class can access those properties and functions. Different objects can hold their own values for properties defined inside the class.
Creating object of a class is simple. The name of the class must be known and object can be created as follows −
class Person: name="" age=0 city="" def display(self): print("Name : ",self.name) print("Age : ",self.age) print("City : ",self.city) p1=Person() p1.name="Rahul" p1.age=20 p1.city="Kolkata" p1.display() print() p2=Person() p2.name="Karan" p2.age=22 p2.city="Bangalore" p2.display() print() p1.display()
In the above implementation, p1=Person() is the object instantiation. p1 is the name of the object . We accessed the properties of the class through object p1 and gave them different values and later called the display function to display values of this object.Later,we do the same for second object p2 and display properties of p2.
At the end, we again call display() for object p1 to show that each object holds its own value of properties and those are independent of the other objects.
Name : Rahul Age : 20 City : Kolkata Name : Karan Age : 22 City : Bangalore Name : Rahul Age : 20 City : Kolkata