Python Programming
Object-Oriented Programming in Python
Object-Oriented Programming
Section titled “Object-Oriented Programming”OOP is a programming paradigm based on objects containing data and methods.
Classes and Objects
Section titled “Classes and Objects”class Dog: species = "Canis familiaris" # Class attribute
def __init__(self, name, age): self.name = name # Instance attribute self.age = age
def bark(self): return f"{self.name} says Woof!"
# Create objectsbuddy = Dog("Buddy", 3)print(buddy.bark()) # Buddy says Woof!Inheritance
Section titled “Inheritance”class Animal: def __init__(self, name): self.name = name
def speak(self): raise NotImplementedError
class Cat(Animal): def speak(self): return f"{self.name} says Meow!"
class Dog(Animal): def speak(self): return f"{self.name} says Woof!"Encapsulation
Section titled “Encapsulation”class BankAccount: def __init__(self, balance): self._balance = balance # Protected self.__pin = "1234" # Private
@property def balance(self): return self._balance
def deposit(self, amount): if amount > 0: self._balance += amount