Learn Python Object-Oriented Programming (OOP) with examples on classes, objects, inheritance, and polymorphism. Master Python OOP concepts for better coding practices.
__str__
, __eq__
, etc.)_variable
or __variable
).@property
and setters for controlled access.Example:
class Temperature:
def __init__(self):
self.__celsius = 0 # Private attribute
@property
def celsius(self):
return self.__celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature too low!")
self.__celsius = value
temp = Temperature()
temp.celsius = 25 # Uses the setter
print(temp.celsius) # Output: 25
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self): # Must be implemented
return self.side ** 2
# shape = Shape() # Error: Can't instantiate abstract class
square = Square(4)
print(square.area()) # Output: 16
__str__
, __eq__
, etc.)Example:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # Overload the '+' operator
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(1, 2)
v2 = Vector(3, 4)
result = v1 + v2
print(result.x, result.y) # Output: 4 6
Example:
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
self.engine = Engine() # Composition: Car "has-a" Engine
my_car = Car()
print(my_car.engine.start()) # Output: "Engine started"
@classmethod
: For factory methods.@staticmethod
: For utility functions.Example:
class Student:
school = "ABC School"
def __init__(self, name):
self.name = name
@classmethod
def change_school(cls, new_school):
cls.school = new_school
@staticmethod
def is_adult(age):
return age >= 18
Student.change_school("XYZ School")
print(Student.school) # Output: "XYZ School"
print(Student.is_adult(20)) # Output: True
self
: Instance methods need self
as the first parameter.Product
, Inventory
, Supplier
.add_product()
, check_stock()
.User
, Post
, Comment
.create_post()
, like_post()
.Student
, Teacher
, Course
.enroll()
, assign_grade()
.BankAccount
class with deposit/withdraw methods.Playlist
class that manages Song
objects.ChessGame
with classes for Board
, Piece
, and Player
.By focusing on these steps, practicing with projects, and avoiding common mistakes, youβll master Python OOP efficiently! ππ‘