Loading notes...
Loading notes...
B.Tech • Chapter 8
B.Tech level module on OOP.
Object-Oriented Programming (OOP) is a paradigm based on 'objects' which contain data (attributes) and code (methods). It promotes modularity and encapsulation.
Advanced Engineering Concepts
In Python, everything is an object. Classes are blueprints. Magic methods (or Dunder methods), like __init__, __str__, and __add__, allow developers to define how their custom objects interact with Python's built-in operators and functions. Encapsulation is achieved via naming conventions (prefixing attributes with _ or __ to trigger name mangling), though Python does not have strict access modifiers like Java.
Code Implementation
class Vector:
def __init__(self, x, y):
self.__x = x # Private attribute (name mangling)
self.y = y
# Getter property
@property
def x(self):
return self.__x
# Operator Overloading
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2) # Uses __add__
# print(v1.__x) # AttributeError