Python is an interpreted, object-oriented, high-level programming language. Its high-level built-in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development and for use as a scripting or glue language to connect existing components.
In Python OOPs concept refers to a programming paradigm that uses objects and classes in programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the programming. The main Python OOPs concept is to bind the data and the functions that work on that together as a single unit so that no other part of the code can access this data.
OOPs in Python
Python is a multi-paradigm programming language. It supports different approaches. One of the popular approaches to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP). The Python OOPs concept focuses on creating reusable code.
This concept is known as DRY (Don’t Repeat Yourself).
5 Key Python OOPs Concept
In Python, the concept of OOP follows some basic principles:
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state.
The class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.
Some points on Python class are:
- Classes are created by keyword class.
- Attributes are the variables that belong to a class.
- Attributes are always public and can be accessed using the dot (.) operator.
Class Definition Syntax
Defining a Class
class Dog: attr1 = “mammal” attr2 = “dog” def fun(self): print(“I’m a”, self.attr1) print(“I’m a”, self.attr2)
An object is an instance of a class. A class is like a blueprint while an object is a copy of the class with actual values. It doesn’t remain an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years old. You can have many dogs to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required.
An object consists of:
- State: It is represented by the attributes of an object. It also reflects the properties of an object.
- Behaviour: It is represented by the methods of an object. It also reflects the response of an object to other objects.
- It gives a unique name to an object and enables one object to interact with other objects.
Defining an Object
class Dog: attr1 = “mammal” attr2 = “dog” def fun(self): print(“I’m a”, self.attr1) print(“I’m a”, self.attr2) Rodger = Dog() print(Rodger.attr1) print(Rodger.attr2) Rodger.fun()
I’m a mammal
I’m a dog
- Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it.
- If we have a method that takes no arguments, then it still has one argument and that is self.
- This is similar to this pointer in C++ and this reference in Java.
The _init_ method is similar to constructors in C++ and Java. Constructors are used to initialize the object’s state. Like methods, a constructor also contains a number of statements that are executed at the time an object is created. It runs as soon as an object of a class is initiated.
class Dog: def _init_(self, name): self.name = name def say_hi(self) print(‘Hello, my name is’, self.name) d = Dog(‘Rodger’) d.say_hi()
Hello, my name is Rodger
A method in Python is somewhat similar to a function, except it is associated with an object/class. A method in Python are very similar to functions except for the following two major differences:
- The method is implicitly used for an object for which it is called.
- The method is accessible to data that is contained within the class.
Structure of Method in Python
class Dog: def _init_(self, name): self.name = name def say_hi(self): print(‘Hello, my name is’, self.name) def walk(): print(‘I can walk) d = Dog(‘Rodger’) d.say_hi() d.walk()
Here, say_hi and walk are methods.
Hello, my name is Rodger
I can walk
Inheritance is the capability of one class to derive or inherit the properties or attributes from another class. The benefits of inheritance are:
- It represents real-world relationships well.
- It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it.
- It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
There are two types of classes in inheritance:
- Parent class is the class being inherited from, also called a base class.
- Child class is the class that inherits from another class, also called derived class.
Create a Parent class
Any class can be a parent class, so the syntax is the same as creating any other class.
class Person: def _init_ (self, fname, lname): self.fname = fname self.name = lname def printname(self): print(self.firstname, self.lastname) x = Person(“Kishore”, “Kumar) x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class.
class Student(Person): pass
Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
When we use the Student class to create an object, and then execute the printname method (since class Student inherits the properties/attributes of Person class).
x = Student(“Ravi”, “Sharma”) x.printname()
Adding _init_() function to Child Class
We can add _init_() function to the Child Class (instead of the pass keyword).
The _init_() function is called automatically every time the class is being used to create a new object.
class Student(Person): def _init_(self, fname, lname): def funtion_1(): . . def function_n():
When you add the _init_() function, the child class will no longer inherit the parent’s class _init_() function. To keep the inheritance of the parent’s _init_() function, add a call to the parent’s _init_() function.
class Student(Person): def _init_(self, fname, name): Person._init_(self, fname, name)
Python also has a super() function that will make the child class inherit all the methods and properties from its parent.
class Student(Person): def _init_(self, fname, name): super()._init_(fname, name)
By using the super() function, you do not have to use the name of the parent class, it will automatically inherit the methods and properties from its parent. You can add extra properties/attributes to a Child Class.
The following code will add a property called graduationyear to the Student class:
class Student(Person): def _init_(self, fname, lname): super()._init_(fname, name) self.graduationyear = 2019
The word polymorphism means having many forms. In programming, polymorphism means the same function name (but performing different activities). Polymorphism in Python can be implemented in any of the following ways:
- Polymorphism with class methods
- Polymorphism with inheritance
Polymorphism with class methods
The below code shows how Python can use two different class types, in the same way. We create a for loop that iterates through a tuple of objects. Then call the methods without being concerned about which class type each object is. We assume that these methods actually exist in each class.
class India(): def continent(self): print(“India is in Asia.”) def capital(self): print(“Capital of India is New Delhi.”) def language(self): print(“Hindi is the most widely spoken language in India.”) class USA(): def continent(self): print(“The USA is in North America.”) def capital(self): print(“Capital of the USA is Washington DC.”) def language(self): print(“English is the most widely spoken language in the USA.”) obj_ind = India() obj_usa = USA() For country in(obj_ind, obj_usa): country.continent() country.capital() country.language()
India is in Asia.
Capital of India is New Delhi.
Hindi is the most widely spoken language in India.
The USA is in North America.
Capital of the USA is Washington DC.
English is the most widely spoken language in the USA.
Polymorphism with Inheritance
In Python, Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. In inheritance, the child class inherits the methods from the parent class. However, it is possible to modify a method in a child class that it has inherited from the parent class. This is particularly useful in cases where the method inherited from the parent class doesn’t quite fit the child class. In such cases, we re-implement the method in the child class. This process of re-implementing a method in the child class is known as Method Overriding.
The following code explains the concept:
class Bird: def intro(self): printf(“There are many types of birds.”) def flight(self): print(“Most of the birds can fly but some cannot.”) class sparrow(Bird): def flight(self): print(“Sparrows can fly.”) class ostrich(Bird): def flight(self): print(“Ostrich cannot fly.”) obj_bird = Bird() obj_spr = sparrow() obj_ost = ostrich() obj_bird.intro() obj_bird.flight() obj_spr.intro() obj_spr.flight() obj_ost.intro() obj_ost.flight()
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostrich cannot fly.
Apart from these high-end features, Python is one of the most suitable kids coding languages to start with. You can master the skills by learning Python through the online courses being offered nowadays.