In this article, we are going to learn about the classes and objects in python.
Python is an object-oriented programming language, which mostly deals with objects and methods. In fact, everything in python is an object, including a class object. The class can be defined as a collection of objects, where the class is the blueprint of the collection of objects. Class is a logical entity that has some specific attributes and methods. Class logically groups data in such a way that code reusability becomes easy. Class is a template or blueprint for how to build an object. A class is a template of entities of some kind. Class defines the state and behavior common to all objects of its kind. Python supports both class objects and instance objects, where the instance is a particular realization of a class.
To create a class, we use a keyword class.
# block of code of class....
Methods , variables , attributes of the class....
Creation of an object in a class:
An object is a real-life entity that has some properties inculcated in it. Objects are basically an encapsulation of data variables and methods acting on that data into a single entity. The collection of these objects is nothing but a class. We can create many objects for a particular class accordingly.
To create an object for a class, we use the following syntax
The syntax for object creation:
#block of code of the class.....
Methods of the class....
And up to so on....
The __init__() function in python( constructor ):
Constructors are generally used for instantiating an object. The task of constructors is to initialize the data members of the class when an object is created. In python, the constructor is always called when an object is created. A constructor can be defined as a special type of method or function which can be used to initialize instances of various members in a class.
We use the constructor to assign values to object properties or other operations that are necessary to do when the object is being created.
Syntax of the constructor:
# Block of code of the class....
# methods of the class....
Object_name=class_name() // this creation of object initializes the constructor
The self parameter is a reference to the current instance of the class and is used to access variables that belong to the class.
It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of any function in the class