Pythonadvanced 10 min
Classes, objects, methods, __init__ and inheritance: model real things in code.
How to define a class, create objects from it, give them data and behaviour, and reuse code with inheritance.
As programs grow, functions and variables floating around get hard to manage. Classes bundle data and the functions that work on it into one unit, which mirrors how we think about things: a bank account, a player, a product.
A class is a blueprint. An object (or instance) is one thing built from the blueprint.
__init__ is the constructor. It runs when you create an object and sets up its data.self is the object itself. Every method receives it as its first parameter.self are attributes; functions in the class are methods.rex = Dog("Rex").Inheritance lets a class reuse another: class Puppy(Dog): gets everything from Dog and can add or override methods. super() calls the parent's version.
Special methods such as __str__ control how an object prints.
Account stores an owner and a balance. deposit and withdraw are methods that change self.balance.__str__ decides what print(a) shows.a: start 100, deposit 50 gives 150, withdraw 30 gives 120. It prints Asha: 120.Savings inherits from Account. super().__init__ runs the parent's setup, then adds a rate.add_interest calls the inherited deposit: 200 plus 10 gives 210.0, so it prints Ravi: 210.0.ValueError, which we catch and print: Error: Not enough money.Add a Dog class with a speak method, then a Puppy subclass that overrides speak.
self in method definitions or when accessing attributes.__init__ (it has two underscores on each side).items=[] in __init__.__init__, self, methods and attributes make up a class.super() calls the parent.Next: handling things that go wrong.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says woof"class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("Not enough money")
self.balance -= amount
def __str__(self):
return f"{self.owner}: {self.balance}"
class Savings(Account):
def __init__(self, owner, balance=0, rate=0.05):
super().__init__(owner, balance)
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate)
a = Account("Asha", 100)
a.deposit(50)
a.withdraw(30)
print(a)
s = Savings("Ravi", 200)
s.add_interest()
print(s)
try:
a.withdraw(1000)
except ValueError as e:
print("Error:", e)