A class is a blueprint
class Student:
school = "AI Pathshala" # Shared by every student
def __init__(self, name, marks): # Runs when a student is created
self.name = name # self means "this particular student"
self.marks = marks
def passed(self):
return self.marks >= 40
riya = Student("Riya", 78)
aman = Student("Aman", 32)
print(riya.name, riya.passed())
print(aman.name, aman.passed())
print(riya.school)Output
Riya True Aman False AI Pathshala
Inheritance and polymorphism
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal): # Dog gets everything Animal has
def speak(self): # And changes this part
return "Woof"
class Puppy(Dog):
def speak(self):
return super().speak() + " (squeaky)"
for pet in [Animal("Generic"), Dog("Sheru"), Puppy("Tommy")]:
print(pet.name, "says", pet.speak())Output
Generic says ... Sheru says Woof Tommy says Woof (squeaky)
Magic methods and privacy
class Basket:
def __init__(self, items):
self._items = items # One underscore: "please don't touch directly"
def __len__(self): # Makes len(basket) work
return len(self._items)
def __str__(self): # Makes print(basket) readable
return "Basket with " + ", ".join(self._items)
def __add__(self, other): # Makes basket + basket work
return Basket(self._items + other._items)
both = Basket(["apple"]) + Basket(["mango", "kiwi"])
print(both)
print(len(both))Output
Basket with apple, mango, kiwi 3
Code challenge
Make a Rectangle class with width and height, and an area() method.
In __init__, store self.width and self.height. Then def area(self): return self.width * self.height.
Finished reading?