Python, as an object-oriented programming language, employs objects to accomplish data operations. Python classes are responsible for the creation of such valuable items.
Python is a programming language that relies on object-oriented programming. Object-oriented programming (OOP) is a high-level programming language that uses objects, classes, and functions to create useful programmes.
Python Classes Explained
In Python, a class is similar to a blueprint from which objects are constructed. Let’s use an automobile as an example to better understand the word.
An automobile is a collection of various elements, such as an engine, wheels, and so on, rather than a single entity. The term “vehicle” refers to a “class,” while the terms “engine” and “wheels” refer to objects.
A class instance is sometimes known as an object, and the process of producing this object is known as instantiation. Each class has objects with numerous arguments that can be used to conduct actions on data.
When creating a class, the following guidelines should be followed:
- Single Responsibility Principle (SRP): According to the Single Responsibility Principle (SRP), a class should only have one purpose.
- Open Closed Responsibility (OCP): The Open Closed Responsibility (OCP) states that the class is open to extension but not to source code modifications.
- Liskov Substitution Responsibility (LSR): The Liskov Substitution Responsibility (LSR) asserts that objects created in the superclass can be replaced with objects created in the subclass.
- Dependency Inversion Principle (DIP): The Dependency Inversion Principle (DIP) asserts that the upper class should be based on the lower class’s abstraction rather than its details.
- Interface Segregation Principle (ISP): The Interface Segregation Principle (ISP) asserts that no section of the code should be dependent on a function that isn’t in use.
Creating Classes in Python
Classes are sort of like templates in which objects are created. The syntax of a class is as follows:
Syntax:
class class_name:
Here,
- class is the keyword for defining class.
- The class_name refers to the class name.
All of a class’s attributes are declared in a new local namespace, and the attributes can be any type of data or function.
A new class object with the same name as the class is established when it is formed. This class object is used to access the class’s different attributes and build new objects for it.
Let’s look at the following example to understand this more clearly:
Example
class Student(object):
def __init__(self, name, age, gender, level, grades=None):
self.name = name
self.age = age
self.gender = gender
self.level = level
self.grades = grades or {}
def setGrade(self, course, grade):
self.grades[course] = grade
def getGrade(self, course):
return self.grades[course]
def getGPA(self):
return sum(self.grades.values())/len(self.grades)
john = Student("Silver", 12, "male", 6, {"math":3.3})
jane = Student("Amanda", 12, "female", 6, {"math":3.5})
print(Silver.getGPA())
print(Amanda.getGPA())
Output
3.3
3.5
Attributes and Methods in Class
Some functionalities are defined by specifying attributes in a class, which act as reservoirs for data and functions linked to those attributes. Methods are the names for the functions.
Attributes
A class attribute refers to a Python variable that belongs to a class rather than a specific object.
The class can be assigned to a variable. Object instantiation is the term for this.
Using the dot operator, you’ll be able to access the characteristics included within the class.
Methods
A method is a function that is “associated” with an object.
In Python, a method is similar to a function, except that it is coupled with objects or classes. Except for two important variations, methods and functions in Python are quite similar.
- The method is applied implicitly to the object for which it is invoked.
- Data included within the class is accessible to the procedure.
Syntax:
class ClassName:
def method_name():
# Method_body
Types of Classes in Python
In Python, there are different varieties of classes in which some are as follows:
- Python Abstract class
- Python Concrete class
- Python Partial Class
Python Abstract Class
An abstract method is a unique method that has a declaration but does not have a need for execution. A class with more than one abstract method is called an abstract class.
Python does not have an abstract class by default, unlike most high-level languages. Instead, this language provides a module named ABC, which allows the creation of the abstract base class.
Example
# Python program invoking a
# method using super()
import abc
from abc import ABC, abstractmethod
class R(ABC):
def rk(self):
print("Abstract Base Class")
class K(R):
def rk(self):
super().rk()
print("Subclass ")
# Driver code
r = K()
r.rk()
Output
Abstract Base Class
Subclass
Python Concrete Class
Concrete classes only have concrete methods, but abstract classes can have both concrete and abstract methods. Although the concrete class implements abstract methods, the abstract base class can also do so by invoking the methods via superclass.
Python Partial Class
A partial class can be used to create a new function that only applies a subset of the statements and keywords you supply it. You can use partial to create a new object by freezing a portion of your function’s statements and keywords. To implement this class, we can use the Functools package.
The __init__() Function
Special functions are class functions that begin with the double underscore and are known as the init () function. The __init__() function is a specific function that is called whenever a new instance of a class is created.
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. When an object is generated from a class, the __init__() function is invoked. The __init__ method is only used by the class to initialise the object’s attributes. It’s solely utilised in the classroom.
The __init__ method, commonly known as constructors in Object-Oriented Programming (OOP), is used to initialise all variables.
The “__init__” method is reserved in Python classes and automatically called when an object is created using a class. It is used to initialise the class’s variables. It is equivalent to a constructor.
- Like every other method, the init method begins with the keyword “def.”
- The first parameter of this method, like any other method, is “self,” but in the case of init, “self” refers to a newly generated object. In contrast, in different methods, “self” refers to the current object or instance associated with that method.
- It is possible to add more parameters.
Example
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Josh')
p.say_hi()
Output
Hello, my name is Josh.
Python Inheritance and Its Types
In Python, there are different inheritance forms depending on the inheritance pattern between a derived class and a base class. The following are some of the inheritance types available in Python:
- Single inheritance: Single inheritance is the sort of inheritance in which a class inherits only one base class.
- Multiple inheritances: Many inheritances refers to a situation in which a class inherits from multiple base classes. Python, unlike other languages, ultimately enables multiple inheritances. All of the base classes are listed as a comma-separated list inside brackets.
- Multilevel inheritance: Multilevel inheritance is when a class inherits a base class, and then another class inherits this previously derived class, resulting in a parent-child relationship class structure.
- Hierarchical inheritance: Hierarchical inheritance occurs when several derived classes inherit a single base class.
- Hybrid inheritance: Hybrid inheritance occurs when one or more of the inheritances mentioned above types are combined.
Example
class polygon:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
class square(polygon):
def __init__(self, side):
polygon.__init__(self, side, side)
MySquare = square(3)
print(MySquare.area())
Output
9
Polymorphism in Python
Polymorphism is the terminology for having several forms. Polymorphism allows for the use of a single interface with several Python data types, classes, and inputs.
Polymorphism is of two types:
- Run-time polymorphism
- Compile-time polymorphism
Run-time Polymorphism
The process of resolving a call to an overridden method at run-time is known as run-time polymorphism. Method overriding is how run-time polymorphism is implemented in Python.
Method overriding enables us to change the implementation of a method declared in the parent class in the child class.
Compile-time Polymorphism
The technique by which the call to the method is resolved at the time of compilation is known as compile-time polymorphism. Method overloading is used to implement compile-time polymorphism.
Using method overloading, one can implement the same functionality of the class with different parameters. However, Compile-time polymorphism is not supported in Python.
Advantages of Using Classes in Python
- Using classes, It is much easier to maintain the data members and methods together and structured in one place.
- Grouping related functions and putting them in one location provides a clear structure to the entire code and improves readability.
- Classes can also be used to override any standard operator.
- The usage of classes allows the code to be reused, making the application more efficient.
Conclusion
Classes are crucial for writing more comprehensive code that is not only efficient but also comprehensible. Classes are usually used in beginner-level and advanced-level programs and reduce frequent errors.
We hope you now have a gist of Python classes and how to use them. Try out the programmes using the examples provided and improve your skills. If you want to learn more about Python as a language, then have a look at this cheat sheet. Alternatively, if you want to become a Python developer, we teach it as part of our Full-Stack Software Development programme. If you want to find out more, schedule a call with our education advisors through the form below.