Introduction
Classes and objects are the core of Object-Oriented Programming. A class defines a blueprint, while an object is a real instance created from it. This is how you build structured, reusable Python applications.
1. Creating a Basic Class
class Car:
pass
mycar = Car()
print(mycar)
2. Adding Attributes (Constructor)
class Car:
def __init__(self, model, year):
self.model = model
self.year = year
c = Car("Subaru Impreza", 2002)
print(c.model, c.year)
3. Adding Methods
class Car:
def __init__(self, model):
self.model = model
def start(self):
print(self.model, "is starting...")
car = Car("Impreza GX")
car.start()
4. The `self` Keyword
self refers to the current object and is required inside class methods.
5. Class Attributes vs Instance Attributes
class Player:
max_hp = 100 # class attribute
def __init__(self, name):
self.name = name # instance attribute
p1 = Player("Kal")
p2 = Player("Ghost")
print(Player.max_hp)
print(p1.name)
6. Inheritance
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def speak(self):
print("Woof!")
d = Dog()
d.speak()
7. Method Overriding
Child classes can replace parent methods.
class Car:
def drive(self):
print("Car driving")
class Subaru(Car):
def drive(self):
print("Subaru with AWD driving!")
s = Subaru()
s.drive()
8. Using super()
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
9. Magic Methods
Special methods that start and end with __.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
v = Vector(5, 8)
print(v)
10. Encapsulation (Private Attributes)
class Bank:
def __init__(self):
self.__balance = 0
def deposit(self, amt):
self.__balance += amt
def get_balance(self):
return self.__balance
b = Bank()
b.deposit(100)
print(b.get_balance())
Summary
- Classes = blueprints.
- Objects = instances from the class.
__init__sets object state.- Methods define behavior.
- Inheritance builds reusable logic.
super()calls parent constructors.- Magic methods customize behavior (
__str__,__len__, etc.). - Private attributes protect internal data.