Object-Oriented Programming
OOP organizes code into classes (blueprints) and objects (instances). Classes bundle data (attributes) and functions (methods) together.
💻 Creating Classes
class Dog:
# Class attribute (shared by all instances)
species = "Canis familiaris"
# Constructor (__init__ initializes instance)
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age
# Instance method
def bark(self):
return f"{self.name} says Woof!"
def description(self):
return f"{self.name} is {self.age} years old"
# Creating objects (instances)
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
print(dog1.bark()) # Buddy says Woof!
print(dog2.description()) # Max is 5 years old
print(dog1.species) # Canis familiaris🔑 Class vs Instance Attributes
class Counter:
count = 0 # Class attribute
def __init__(self, name):
self.name = name # Instance attribute
Counter.count += 1 # Modify class attribute
@classmethod
def get_count(cls):
return cls.count
c1 = Counter("First")
c2 = Counter("Second")
print(Counter.get_count()) # 2🎯 Key Takeaways
- class: Blueprint for creating objects
- __init__: Constructor method
- self: Reference to instance
- Instance attributes: Unique to each object
- Class attributes: Shared by all instances
- Methods: Functions inside classes
- @classmethod: Methods that work with class