Topics in Python Programming
Variables & TypesControl FlowFunctionsOOP & ClassesFile I/ONumPy & PandasWeb ScrapingDecoratorsList ComprehensionVirtual Environments
🐍 Object-Oriented Python
Classes & Objects in Python
Python is a multi-paradigm language that fully supports OOP. You define classes using the class keyword, and create objects (instances) from classes.
Key Concepts:
- Class: Blueprint (template) for creating objects
- Object: An instance of a class with its own attribute values
- __init__: Constructor that initialises object attributes
- Inheritance: Derive a new class from an existing class
- Dunder methods: __str__, __repr__, __len__, __add__ etc.
Tip: Use @dataclass from Python 3.7+ to auto-generate __init__ and __repr__ for simple value-holding classes.
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}"
class Dog(Animal):
def fetch(self):
return f"{self.name} fetches the ball!"
rex = Dog("Rex", "Woof")
print(rex.speak()) # Rex says Woof
print(rex.fetch()) # Rex fetches the ball!Video: Python OOP – Classes, Inheritance, Dunder Methods
Watch on YouTubeQuick Quiz – Python Programming
Doubt & Discussion
Be respectful. No spam.
Loading discussion…
