Object-oriented programming (OOP) is a programming concept based on the objects that interact with each other to perform the functions. Each object can be characterized by a behaviour and state. An object keeps the current state and the behavior in the fields and methods. It emphasizes the DRY(Don’t Repeat Yourself) Principle.
For instance, an object could represent an email with properties like subject, title, body and behaviors such as attachments, sending,organising.
OOP categorizes entities as software objects that have some data associated with them to perform operations upon.
Another common programming concept is Procedural Oriented Programming(POP), which structures a program like a food recipe which provides a finite number of steps, in the form of functions or code blocks, that flow sequentially in order to get the final result.
Major OOPs Concepts In Python
Classes
A class defines the attributes and behaviour of an object.For example if you have an Employee class, it can have attributes like name,salary and age, whereas its behaviour can include functions such as deduct or increment salary or calculate bonus etc.
Objects
Objects are the instances of classes or derived attributes and behaviours from class with actual data.
Methods
Functions under classes are known as methods.They define the behaviour of class.
Here is an example of classes and objects…
class Article: def __init__(self, title, content, author): self.title = title self.content = content self.author = author def represent(self): return f'{self.title,self.content,self.author}’ art_1 = Article(‘Automate the Boring Stuff’, ‘Practical Programming..’, ‘AL Sweigart’) art_2= Article(‘Python Tricks’, ‘A Buffet of Awesome Python..’, ‘Dan Bader’) print(art_1.represent()) |
Here the Article is a class and post_1 and post_2 are the objects or instances of the class.The __init__ function is a constructor that initialises or defines the attributes of the class.
Setting self.title=title or other attributes like this enables you to use the passed arguments using self.title in other parts of the class.
For instance if you change it to
self.heading = title |
Then you would use it as
def represent(self): return f'{self.heading,self.content,self.author}’ |
The output of the code is
(‘Automate the Boring Stuff’, ‘Practical Programming..’, ‘AL Sweigart’) |
__str__ and __repr__ are the methods that will be invoked by default just like __init__ method to print the data of an instance when the object is called so you can avoid defining a custom represent method. These methods are also known as dunder or magic methods.
Checkout this Python Training Online by FITA. FITA provides a complete Python course where you will be building real-time projects like Bitly and Twitter bundled with Django, placement support and certification at an affordable price.
Inheritance
You might have some inheritance or resemblance of behaviours in you like your parents.Just like this, you can inherit properties of one class from another.The newly inherited class is a derived or child class and the former as base or Parent class.
Example Of Inheritance
class Post(Article): def __init__(self,title,content,author, image): super().__init__(title,content,author) self.image = image def ret_image(self): try: img = Image.open(self.image) img.show() x = img.format y = img.mode return f’ Format: {x} Mode: {y}’ except IOError: pass post_1 = Post(‘Learn Python the Hard Way’, ‘A Very Simple Intro..’, ‘AL Sweigart’, ‘book1.png’) post_2 = Post(‘Python Tricks’, ‘A Buffet of Awesome Python Features’, ‘Dan Bader’, ‘book2.png’) print(post_2.ret_image()) |
Here we just needed to add another attribute and method and the rest of the attributes and methods are added to the child class by passing the Article argument to class name and defining super() method.
The output for the above program will include this and opens the image in the gallery
Format: PNG Mode:RGBA |
The different types of inheritance are single-level, multi-level and hierarchical inheritance.
Polymorphism
Polymorphism is when you use a class method in different ways or in more than one way.There are two types of polymorphism
Here is an example of a program to have a better understanding of Polymorphism..
class FullTimeEmployee: def __init__(self, name, position, hours, salary): self.name = name self.position = position self.hours = hours self.salary = salary def bonus(self): return (self.salary * 0.5) class PartTimeEmployee(FullTimeEmployee): def __init__(self, name, position, hours, salary): super().__init__(name, position, hours, salary) def bonus(self): return (self.salary * 0.1) # common interface def inc_bonus(object): x = object.bonus() print(f'{object.name}\’s bonus will be {x}’) # instantiate objects emp_1 = FullTimeEmployee(‘Atufa’, ‘Frontend Developer’, 6, 1000) emp_2 = PartTimeEmployee(‘Shireen’, ‘Content Writer’, 8, 2000) # passing the object print(inc_bonus(emp_1)) print(inc_bonus(emp_2)) |
In the above code, the classes PartTimeEmployee and FullTimeEmployee are the Base and the derived classes respectively. A same method bonus works differently in both the classes, it returns a 50 percent bonus for a full time employee and a 10 percent bonus for a part time employee.
A common function inc_bonus calls the same bonus method of the class. The output for the above example
Atufa’s bonus will be 500.0 Shireen’s bonus will be 200.0 |
Encapsulation
Encapsulation in simple terms is to make the methods and attributes private or protected and give a level of security to be accessed outside the class.
In most of the other languages, the keywords public, private and protected are used to give a defined level of access outside the class, whereas in Python the _ (single underscore),__(double underscore) or no underscore is used before the attribute to define protected, private and public respectively. For instance,
class Post: def __init__(self, title, content, author, image): self.title = title self._content = content self.__author = author self.image = image def ret_image(self): img = Image.open(self.image) img.show() emp_1 = Post(‘Automate The Boring Stuff’, ‘Practical Programming for..’, ‘atufa’,’default.jpg’) print(emp_1.title) print(emp_1.content) print(emp_1.author) |
You would get an AttributeError: ‘Post’ object has no attribute ‘content’.But when you can change it to this you can access it.
print(emp_1._content) |
But now you will get the same error for other attribute
AttributeError: ‘Post’ object has no attribute ‘__author’
But to access this you will need to define Getter method, and a Setter method to modify it.
Here’s how you would do it.
def show_author(self): print(self.__author) def modify_author(self, new_author): self.__author = new_author emp_1.show_author() emp_1.modify_author(‘Shireen’) |
The show_author is a custom getter method and modify_author is a custom setter method.
There are built-in decorators like @property and setter method in python to do this.
Data Abstraction
Abstraction is wherein the user is kept unaware of the code that is used for implementation, for instance, when you are buying a brand new phone, it is one thing for you, although there are many individual parts in this. Abstraction allows users to use the phone without knowing the complexity of the parts that form the phone.
This was all about Object Oriented Programming In Python. To get in-depth knowledge of Python along with its various applications and real-time projects, you can enroll in Python Training Institute in Chennai or Python Training in Bangalore by FITA at an affordable price, which includes certification, support and career guidance assistance.