1. Classes & Objects
Classes are blueprints. Objects are instances. Use self to refer to instance inside class.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy", 3)
my_dog.bark()
Buddy says Woof!
2. Attributes & Methods
Instance attributes (self.name) vs class attributes (shared). Methods operate on instances.
Dog Class:
โโโ
โโโ
โโโ
โโโ
species = "Canine" (class attr)โโโ
self.name (instance attr)โโโ
bark() (method)
class Car:
wheels = 4 # Class attribute
def __init__(self, brand):
self.brand = brand # Instance attribute
def start(self):
print(f"{self.brand} engine started")
car1 = Car("Toyota")
print(Car.wheels) # 4
car1.start()
4
Toyota engine started
3. Inheritance
Child classes inherit from parent using (ParentClass). Override methods as needed.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def speak(self): # Override
print(f"{self.name} says Woof!")
class Cat(Animal):
def speak(self):
print(f"{self.name} says Meow!")
dog = Dog("Rex")
cat = Cat("Whiskers")
dog.speak()
cat.speak()
Rex says Woof!
Whiskers says Meow!
4. Encapsulation (Private Attributes)
Use single (_) or double (__) underscore for private attributes. Convention, not strict enforcement.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
# print(account.__balance) # AttributeError
1500
5. Polymorphism
Same method name, different behaviors in child classes. Method overriding enables this.
animals = [Dog("Rex"), Cat("Whiskers")]
for animal in animals:
animal.speak() # Different outputs!
OOP Concepts Quick Reference
| Concept | Keyword/Syntax | Example | Purpose |
|---|---|---|---|
| Class | class Name: | Dog | Blueprint |
| Constructor | __init__(self) | self.name = name | Initialize |
| Inheritance | class Child(Parent): | Dog(Animal) | Reuse code |
| Private | self.__attr | __balance | Hide data |
| Method Override | Same name in child | speak() | Polymorphism |
๐ง OOP Quiz (8 Questions)
Q1: Constructor method name?
Q2: Refers to instance inside class?
Q3: Inheritance syntax?
Q4: Private attribute prefix?
Q5: Class attribute access?
Q6: Same method, different behavior?
Q7: Child class modifies parent method?
Q8: Create object from class?