Oops in Python
Oops in Python
Principles of OOP
Class
Objects
Polymorphism
Encapsulation
Inheritance
Data Abstraction
Class
In Python, a class is a blueprint for creating objects. A class defines
the attributes and methods of its objects. A class defines what an
object of that class will look like and how it will behave.
What is an Object ?
An object is an instance of a class. It represents a specific item that is
created based on the class definition. An object has its own unique
identity, state, and behavior.
class Person:
# Other lines
class Person:
def __init__(self, name, age):
""" Initializing attributes """
self.name = name
self.age = age
Creating Object
Methods
Methods are functions that are defined inside a class and are called
on objects of that class.
They have access to the object’s attributes and can modify them.
class Person:
def __init__(self, name, age):
""" Initializing attributes """
self.name = name
self.age = age
def get_info():
"""Method"""
print("Name:", name, " Age:", age)
Class Methods
To call a class method in Python, you use the class name followed by
the method name in dot notation.
class Circle:
class-level variables
pi = 3.14
def calculate_area(self):
return Circle.pi * self.radius * self.radius
@classmethod
def change_pi(cls, new_pi):
cls.pi = new_pi
Static Methods
Static methods are defined using the@staticmethod decorator and are
not bound to the class but rather to the instance of the class.
They are similar to regular functions. But they are placed inside a
class for organizational purposes.
class MathUtils:
@staticmethod
def square(x):
return x * x
@staticmethod
def cube(x):
return x * x * x
result2 = MathUtils.cube(3)
print(result2) # Output: 27
Static methods can be accessed directly from the class itself by using
dot notation.
Polymorphism
Polymorphism allows objects of different types to be treated as
objects of a common superclass. Subclasses have access to all
methods and attributes.
class Person:
def __init__(self, name):
self.name = name
def get_details(self):
return f"Name: {self.name}"
class Employer(Person):
def __init__(self, name, company):
super().__init__(name)
self.company = company
def get_details(self):
return Name: {self.name}, Company: {self.company}"
Encapsulation
Encapsulation helps protect the data from unauthorized access and
ensures proper maintenance.
Some common access modifiers used in Python:
class BankAccount:
def __init__(self, account_number, balance):
self.account_number = account_number
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
Conclusion
Finally, Object-Oriented Programming (OOP) is a strong paradigm
that enables developers to create and arrange code in a more
ordered and modular fashion. Python, as an object-oriented
language, offers extensive support for OOP principles.