Forum

Learn Python Classe…
 
Notifications
Clear all

Learn Python Classes

1 Posts
1 Users
0 Reactions
9 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

 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 object
  • self 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. 


   
Quote
Share: