You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Basic Class StructureclassCar:
# Class variable (shared by all instances)total_cars=0# Constructor (initialize instance)def__init__(self, brand: str, year: int):
self.brand=brand# Public attributeself._year=year# Protected attribute (convention)self.__running=False# Private attribute (name mangling)Car.total_cars+=1# Access class variable# Instance methoddefstart_engine(self):
self.__running=Trueprint("Engine started!")
# Property decorator (getter)@propertydefyear(self):
returnself._year# Property setter@year.setterdefyear(self, value):
ifvalue>1900: # Data validationself._year=value# Class method (works with class itself)@classmethoddefget_total_cars(cls):
returncls.total_cars# Static method (utility function)@staticmethoddefvalidate_brand(brand):
returnbool(brandandbrand.strip())
# Creating and Using Objectsmy_car=Car("Toyota", 2020) # Create new Carmy_car.start_engine() # Call methodyear=my_car.year# Use propertymy_car.year=2021# Use settertotal=Car.get_total_cars() # Use class method
fromabcimportABC, abstractmethod# Abstract Base ClassclassShape(ABC):
def__init__(self, color: str):
self.color=color@abstractmethoddefcalculate_area(self) ->float:
"""Must be implemented by subclasses"""pass@abstractmethoddefcalculate_perimeter(self) ->float:
"""Must be implemented by subclasses"""pass# Concrete methoddefdescribe(self):
print(f"This is a {self.color} shape")
# Concrete ClassclassCircle(Shape):
def__init__(self, color: str, radius: float):
super().__init__(color)
self.radius=radius# Implement abstract methodsdefcalculate_area(self) ->float:
return3.14159*self.radius**2defcalculate_perimeter(self) ->float:
return2*3.14159*self.radius# Using Abstract Classescircle=Circle("red", 5)
area=circle.calculate_area() # Use implemented methodcircle.describe() # Use inherited method
Polymorphism
# Polymorphic ClassesclassVehicle:
defmove(self):
print("Vehicle moving")
classCar(Vehicle):
defmove(self):
print("Car driving")
classBoat(Vehicle):
defmove(self):
print("Boat sailing")
# Duck Typing (Python's approach to polymorphism)defstart_journey(vehicle):
vehicle.move() # Will work with any object that has move()# Using Polymorphismcar=Car()
boat=Boat()
# Same function, different behaviorsstart_journey(car) # "Car driving"start_journey(boat) # "Boat sailing"# Duck Typing ExampleclassRobot:
defmove(self):
print("Robot walking")
start_journey(Robot()) # Works because Robot has move()
Encapsulation
# Fully Encapsulated ClassclassBankAccount:
def__init__(self, account_number: str, owner: str):
self.__account_number=account_number# Privateself.__owner=owner# Privateself.__balance=0.0# Private# Property for read-only access@propertydefbalance(self) ->float:
returnself.__balance# Property for read-only access@propertydefowner(self) ->str:
returnself.__owner# Public methods for controlled accessdefdeposit(self, amount: float) ->bool:
ifamount>0:
self.__balance+=amountself.__notify_owner("Deposit successful")
returnTruereturnFalsedefwithdraw(self, amount: float) ->bool:
ifamount>0andamount<=self.__balance:
self.__balance-=amountself.__notify_owner("Withdrawal successful")
returnTruereturnFalse# Private helper methoddef__notify_owner(self, message: str):
print(f"Notification to {self.__owner}: {message}")
# Using Encapsulated Classaccount=BankAccount("123456", "John Doe")
account.deposit(1000) # Use public methodbalance=account.balance# Use property
Special Methods
# Class with Special MethodsclassPoint:
def__init__(self, x: float, y: float):
self.x=xself.y=y# String representationdef__str__(self) ->str:
returnf"Point({self.x}, {self.y})"# Detailed string representationdef__repr__(self) ->str:
returnf"Point(x={self.x}, y={self.y})"# Addition operatordef__add__(self, other) ->'Point':
returnPoint(self.x+other.x, self.y+other.y)
# Equality comparisondef__eq__(self, other) ->bool:
ifnotisinstance(other, Point):
returnFalsereturnself.x==other.xandself.y==other.y# Less than comparisondef__lt__(self, other) ->bool:
returnself.x<other.x# Length (magnitude)def__len__(self) ->int:
returnint((self.x**2+self.y**2) **0.5)
# Make object callabledef__call__(self, factor: float) ->'Point':
returnPoint(self.x*factor, self.y*factor)
# Using Special Methodsp1=Point(2, 3)
p2=Point(3, 4)
print(p1) # Uses __str__sum_point=p1+p2# Uses __add__scaled=p1(2) # Uses __call__