Introduction
In object-oriented programming, the concept of class and object is very essential. In Python, we also find such object-oriented characteristics. A class is a description of a set of objects that share the same properties (attributes), behaviour (operations), kind of relationships, and semantics. An object is an instance of a class. Here we will be discussing different properties of a class and object as well as how a class is defined, and an object is created.
Also see, Python Round Function.
Recommended topics, Floor Division in Python, and Convert String to List Python
Class
A class can be considered a user-defined blueprint from which objects are created. Classes are used to bundle data and functionalities together so that their objects can be created or classified under different classes based on their functionalities. Objects of each class can have their attributes to maintain the state, and their state values can be modified using the member functions.
Let’s understand this concept through an example.
If we consider student as a class, the student class has name, age, enrollment_id as its attributes, and study, eat, sleep as its behaviour.
Defining class
#a class to denote student of CSE department
class Student:
#calss attribute
department="CSE"
#constructor in Python
def __init__(self,name,enr_id):
#instance variable
self.name=name
self.enr_id=enr_id
def get_name(self):
return self.name
def get_id(self):
return self.enr_id
#object of Student class
student1= Student("Dhruv",5105133)
student1.get_name()
Data members(attributes)
Attributes are variables of a class. Attributes are public and can be accessed using the dot(.) operator. For example, to access the department attribute of the Student class we can use Student.department.
Self parameter
All class methods have self as their first parameter. We don’t provide any value to this parameter when we call a method. It is similar to this reference in C++, Java.
Constructor in Python: __init__( ) method
init method works as a constructor in Python. It is used to initialize objects of a class. This method is executed at the time of object creation.
# constructor in Python for Student class
def __init__(self,name,enr_id):
#instance variable
self.name=name
self.enr_id=enr_id
Also See, Intersection in Python