oops concepts in python

Object-oriented programming (OOP) is a paradigm that organizes data and behavior into reusable units called objects. OOP makes code more modular, readable, and maintainable. Python is a multi-paradigm language that supports OOP along with other paradigms such as procedural and functional programming. In this article, we will explore the basic OOPS concepts in Python and how they can be used to write better code.

#1- Classes and Objects

A class is a blueprint of oops concepts in python that defines the attributes and methods of a type of object. An attribute is a variable that belongs to an object, and a method is a function that operates on an object. An object is an instance of a class that has its own state and behavior. To create a class in Python, we use the class keyword followed by the class name and a colon. For example, we can define a class called Person that has two attributes: name and age.

class Person:
# constructor method
def _init_ (self, name, age):
# assign attributes
self.name = name
self.age = age

The _init_ method is a special method that is called when an object is created. It takes the self parameter, which refers to the current object, and any other parameters that are needed to initialize the object.

The self parameter is mandatory for all methods in a class, and it must be the first parameter. To create an object of a class, we use the class name followed by parentheses and pass the arguments for the _init_ method. For example, we can create an object of the Person class and assign it to a variable called p1.

p1 = Person(“Alice”, 25)

We can access the attributes and methods of an object using the dot (.) operator. For example, we can print the name and age of p1 using the following code.

print(p1.name) # Alice
print(p1.age) # 25

We can also define methods in a class that perform some actions on the object. For example, we can define a method called greet that prints a greeting message using the name attribute of the object.

class Person:
# constructor method
def _init_(self, name, age):
# assign attributes
self.name = name
self.age = age

# greet method
def greet(self):
# print a greeting message
print(f”Hello, my name is {self.name} and I am {self.age} years old.”)

We can call the greet method on the p1 object using the dot operator.

p1.greet() # Hello, my name is Alice and I am 25 years old.

#2- Inheritance and Polymorphism

Inheritance is a mechanism that allows a class to inherit the attributes and methods of another class. The class that inherits from another class is called the subclass or child class, and the class that is inherited from is called the superclass or parent class.

Inheritance enables code reuse and reduces redundancy. To create a subclass in Python, we use the class name followed by parentheses and the name of the superclass. For example, we can create a subclass called Student that inherits from the Person class.

class Student(Person):
# constructor method
def _init_(self, name, age, school):
# call the constructor of the superclass
super( )._init_(name, age)
# assign additional attribute
self.school = school

The super( ) function returns a reference to the superclass, and we can use it to call the methods of the superclass. In this case, we call the _init_ method of the Person class to initialize the name and age attributes, and then we assign an additional attribute called school to the Student object.

In oops concepts in python, we can create an object of the Student class and access its attributes and methods as follows.

s1 = Student(“Bob”, 18, “ABC High School”)
print(s1.name) # Bob
print(s1.age) # 18
print(s1.school) # ABC High School
s1.greet() # Hello, my name is Bob and I am 18 years old.

Notice that the Student object inherits the greet method from the Person class, and we can call it without defining it in the Student class. This is an example of code reuse through inheritance. However, sometimes we may want to modify or override the behavior of a method in the subclass. This is called polymorphism, which means having different forms or behaviors for the same method. To override a method in the subclass, we simply define it with the same name and parameters as the superclass. For example, we can override the greet method in the Student class to include the school attribute in the greeting message.

class Student(Person):
# constructor method
def _init_(self, name, age, school):
# call the constructor of the superclass
super()._init_(name, age)
# assign additional attribute
self.school = school

# override the greet method
def greet(self):
# print a modified greeting message
print(f”Hello, my name is {self.name} and I am {self.age} years old. I study at {self.school}.”)

Now, if we call the greet method on the s1 object, we will get a different output.

s1.greet() # Hello, my name is Bob and I am 18 years old. I study at ABC High School.

This is an example of polymorphism, where the greet method has different behaviors for the Person and Student classes.

Read More From The Teksol: Software Development Tool List

#3- Encapsulation and Abstraction

Encapsulation is a mechanism that hides the internal details of an object and exposes only the relevant information and functionality to the outside world. It ensures data integrity and security, and prevents unauthorized access and modification.

In Python, we can use underscores ( _ ) to indicate the level of access for an attribute or a method. A single underscore ( _ ) means that the attribute or method is protected, and it should not be accessed or modified directly by the outside world.

A double underscore ( _ _ ) means that the attribute or method is private, and it is inaccessible and invisible to the outside world. For example, we can define a class called BankAccount that has two private attributes: balance and pin.

class BankAccount:
# constructor method
def _init_(self, balance, pin):
# assign private attributes
self.__balance = balance
self.__pin = pin

The balance and pin attributes are private, and they cannot be accessed or modified directly by the outside world. For example, if we try to print the balance attribute of an object of the BankAccount class, we will get an error.

b1 = BankAccount(1000, 1234)
print(b1.__balance) # AttributeError: ‘BankAccount’ object has no attribute ‘__balance’

Access or Modification:

To access or modify the private attributes, we need to define public methods that act as getters and setters. A getter is a method that returns the value of a private attribute, and a setter is a method that updates the value of a private attribute. For example, we can define a getter method called get_balance and a setter method called set_balance for the balance attribute.

class BankAccount:
# constructor method
def _init_(self, balance, pin):
# assign private attributes
self.__balance = balance
self.__pin = pin

# getter method for balance
def get_balance(self):
# return the value of balance
return self.__balance

# setter method for balance
def set_balance(self, new_balance):
# update the value of balance
self.__balance = new_balance

Now, we can use the getter and setter methods to access and modify the balance attribute.

b1 = BankAccount(1000, 1234)
print(b1.get_balance()) # 1000
b1.set_balance(2000)
print(b1.get_balance()) # 2000

We can also define other public methods that perform some operations on the object, such as depositing or withdrawing money. For example, we can define a method called withdraw that takes the amount and the pin as parameters, and checks if the pin is correct and the balance is sufficient before withdrawing the money.

class BankAccount:
# constructor method
def _init_(self, balance, pin):
# assign private attributes
self.__balance = balance
self.__pin = pin

# getter method for balance
def get_balance(self):
# return the value of balance
return self.__balance

# setter method for balance
def set_balance(self, new_balance):
# update the value of balance
self.__balance = new_balance

# withdraw method
def withdraw(self, amount, pin):
# check if the pin is correct
if pin == self.__pin:
# check if the balance is sufficient
if amount <= self.__balance:
# withdraw the money
self.__balance -= amount
# print a success message
print(f”You have withdrawn {amount} successfully. Your new balance is {self.__balance}.”)
else:
# print an error message
print(“Sorry, you do not have enough balance to withdraw this amount.”)
else:
# print an error message
print(“Sorry, the pin you entered is incorrect.”)

oops concepts in python: We can use the withdraw method to withdraw money from the b1 object.

b1.withdraw(500, 1234) # You have withdrawn 500 successfully. Your new balance is 1500.
b1.withdraw(2000, 1234) # Sorry, you do not have enough balance to withdraw this amount.
b1.withdraw(100, 4321) # Sorry, the pin you entered is incorrect.

This is an example of encapsulation, where the private attributes are hidden from the outside world and can only be accessed or modified through the public methods.

The public methods also provide some validation and error handling to ensure data integrity and security. Encapsulation also enables abstraction, which is the process of hiding the implementation details and exposing only the essential features and functionality to the user. Abstraction makes the code more understandable and easy to use, and reduces the complexity and dependency of the system.

For example, the user of the BankAccount class does not need to know how the balance and pin attributes are stored and manipulated internally, and can simply use the public methods to perform the desired operations.

Conclusion

In this article, we have learned about the basic OOPS concepts in Python, such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. We have seen how these concepts can help us write more modular, readable, and maintainable code, and how they can improve the design and functionality of our programs.

OOPS concepts in python is a powerful and widely used paradigm that can enhance our coding skills and enable us to create more complex and robust applications. We hope you have enjoyed this article written by The Teksol and learned something new and useful.

Share it on

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *