Key Elements of OOP in Python
Inheritance: Helps achieve code reusability.
Encapsulation: Data hiding possible through name mangling and property setters.
Polymorphism: Achieved through method overloading, overriding, and duck typing.
Terminology
Class: Blueprint for creating objects.
Object: Instance of a class.
Method: Function defined within a class.
Attribute: Data bound to an object or class.
Code Example: OOP in Python
class Shape:
def \_\_init\_\_(self, name):
self.name = name
def describe(self):
return f"I am a {self.name}."
class Circle(Shape):
def \_\_init\_\_(self, radius):
super().\_\_init\_\_("circle")
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Square(Shape):
def \_\_init\_\_(self, side_length):
super().\_\_init\_\_("square")
self.side_length = side_length
def area(self):
return self.side_length ** 2
Create instances and invoke methods
circle = Circle(5)
print(circle.describe())
print("Area of the circle:", circle.area())
square = Square(4)
print(square.describe())
print("Area of the square:", square.area())