Notifications
Clear all
Topic starter 01/08/2025 11:38 pm
Python classes are the building blocks of object-oriented programming (OOP)—they let you create your own custom types that bundle data and behavior together.
🏗️ Defining a Class
Start with the class
keyword and a name:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
__init__
is the constructor method that gets called when you create an objectself
refers to the current instance—like “this” in other languages
🐶 Creating an Object
my_dog = Dog("Fido", "Labrador")
print(my_dog.name) # Fido
print(my_dog.breed) # Labrador
🧠 Adding Methods (Functions Inside Classes)
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def speak(self):
print(f"{self.name} says woof!")
Call the method with:
my_dog.speak() # Fido says woof!
🧬 Inheritance
You can build a new class based on an existing one:
class Puppy(Dog):
def speak(self):
print(f"{self.name} squeaks!")
💡 Bonus Concepts
__str__
method defines how the object is printed@classmethod
and@staticmethod
offer alternate ways to define behavior- Private attributes: prefix with
_
(convention) or__
(name mangling)
class Cat:
def __init__(self, name):
self._mood = "grumpy"
self.__secret = "naps all day"
Python makes OOP both powerful and intuitive.