Classes in Python
Classes in Python holds the same concept as classes in Java. It can be defined as a blueprint or a map which holds all the codes necessary for our execution. If different instances arise, then we can always create a different copy of this class which is called as objects. Objects perform the task accordingly by using the same set of instructions.
The syntax is followed by:
class Student: name = input("Enter your name") roll = int(input("Enter your Roll No.")) def display (self): print("Name:%s\t Roll No: %d\n", self.name, self.roll)
A class is defined using the class keyword followed by the class name. After the colon mark, we can include the required general instructions we want to execute.
However, to establish communication between the two classes, we need to parameterize the class. And this is done by initializing the constructor for the class using __init__().
The syntax is as follows:
class Student: def __init__(self, name, roll): self.name = name self.roll = roll def display(self): print("Name:", self.name, "Roll No", self.roll)
We will learn more about this concept in the following section.
Objects in Python
Objects are required when we want to create separate instances of a class. It means that a class contains a generalized set of instructions to be performed. And those generalized instructions are treated like multiple copies when an object is created.
Thus by creating objects, we provide specific values to these general instructions and hence accordingly perform the different set of tasks.
The following example will make it clear:
class Student: def __init__(self, name, roll): self.name = name self.roll = roll def display(self): print("Name:", self.name, "Roll No", self.roll) stud1 = Student("Tony", 3000) stud1.display() stud2 = Student("Mario", 9999) stud2.display()
Note that in python, a default argument is added to every function inside a class called as self. This argument is referenced and used with other variables of the class.
We cannot use classes until and unless the objects are defined. By creating objects, we can pass the parameters accordingly to the class. This feature enables us to reuse the code as much as we want.
Classes and objects serve as a handy tool in implementing object-oriented programming in Python. Some features include:
- Data Abstraction.
- Class level Inheritance.
- Code Reusability.