Python OOP
Here's a simple, clear explanation of Python Object-Oriented Programming (OOP) concepts:
🧠 Core OOP Concepts in Python
1. Class
A blueprint for creating objects.
class Car:
pass
2. Object
An instance of a class.
my_car = Car()
print(type(my_car)) # <class '__main__.Car'>
3. init Method (Constructor)
Used to initialize an object’s data (runs when object is created).
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
my_car = Car("Toyota", "Red")
print(my_car.brand) # Toyota
4. Self
Refers to the current object inside the class.
class Car:
def __init__(self, brand):
self.brand = brand # self.brand is object’s variable
5. Method
Functions inside a class.
class Car:
def __init__(self, brand):
self.brand = brand
def drive(self):
print(f"{self.brand} is driving!")
car1 = Car("Honda")
car1.drive() # Honda is driving!
6. Encapsulation
Hides internal details. You can make attributes private using _
or __
.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private variable
def get_balance(self):
return self.__balance
account = BankAccount(1000)
print(account.get_balance()) # 1000
7. Inheritance
A class can inherit properties from another class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.speak() # Inherited method
d.bark()
8. Polymorphism
Same method name, different behavior.
class Bird:
def sound(self):
print("Tweet")
class Cat:
def sound(self):
print("Meow")
for animal in (Bird(), Cat()):
animal.sound()
Comments
Post a Comment