In the Python programming language, the user-defined classes define new types of objects that extend the base set. In this article, I’ll walk you through a tutorial on Python classes.
Introduction to Classes in Python
Python supports both procedural and object-oriented programming paradigms. While the procedural paradigm focuses on the creation of functions, the object-oriented paradigm centres on the use of objects and classes. An object is a software entity that stores data.
Also, Read – 100+ Machine Learning Projects Solved and Explained.
A class is a plan that describes the data stored in an object and defines the operations that can be performed on the object. Objects are created or instantiated from classes, and each object is known as an instance of the class from which it was created.
Python Classes Tutorial
Python, like all object-oriented programming languages, allows programmers to define their classes. A class definition is an instruction composed of a header and a body. The class header contains the class keyword followed by an identifier used to name the class. The body of the class definition contains one or more method definitions, all of which must be indented to the same level of indentation.
Say, for example, you want to have some type of object that models employees. While there is no specific kernel type in Python, the following user-defined class can do the trick:
class worker: def __init__(self, name, payment): self.name = name self.payment = payment def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.payment *= (1.0 + percent)
This class defines a new type of object that will have the name and payment attributes, as well as two behaviour bits encoded as functions. Calling the class as a function generates instances of our new type, and the methods of the class automatically receive the instance being processed by a given method call:
Aman = worker("Aman Kharwal", 1000000) Akanksha = worker("Akanksha Kharwal", 500000) print(Aman.lastName()) print(Akanksha.lastName()) Aman.giveRaise(.50) print(Aman.payment)
Kharwal Kharwal 1500000.0
The bigger story of classes is that their inheritance mechanism supports software hierarchies that lend themselves to customization by extension. We extend the software by writing new classes, not by modifying what is already working.
Summary
You should also know that classes are an optional feature of Python programming language as the other simpler built-in types like lists and dictionaries are often better tools than user-defined classes. But using Python classes improves your coding skills and is important for coding interviews as a Python developer.
Hope you liked this article on a tutorial on Python classes. Please feel free to ask your valuable questions in the comments section below.