๐Ÿ“ฆ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

ConceptKeyword/SyntaxExamplePurpose
Classclass Name:DogBlueprint
Constructor__init__(self)self.name = nameInitialize
Inheritanceclass Child(Parent):Dog(Animal)Reuse code
Privateself.__attr__balanceHide data
Method OverrideSame name in childspeak()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?