Part 09 / Topic 2 of 12
Class and object, __init__, self
class Name:defines a class. Class names use PascalCase (BankAccount, notbank_account).Name(...)creates an object. Python then calls the special method__init__to set it up.__init__is the constructor (the setup code that runs when an object is made).selfis the object being set up or used. Python passes it in for you; you never pass it yourself.self.name = namecreates an instance attribute: a value that belongs to that one object.
Think of filling in a new customer form at a bank: every customer gets their own form (object), and the fields (attributes) hold their own details.
Real-world example: customers of a mobile shop.
class Customer:
def __init__(self, name: str, city: str):
self.name = name # instance attribute
self.city = city
self.orders = [] # every customer starts with an empty list
ravi = Customer("Ravi", "Pune")
meera = Customer("Meera", "Chennai")
ravi.orders.append("Earphones")
print(ravi.name, ravi.city, ravi.orders) # Ravi Pune ['Earphones']
print(meera.name, meera.city, meera.orders) # Meera Chennai []
print(type(ravi).__name__) # Customer
print(isinstance(meera, Customer)) # True
ravi and meera are built from the same class but hold their own data.
If you print(ravi) you get something like <__main__.Customer object at 0x...>. Section 8 shows how to make that readable.
๐ Going deeper:
selfis only a habit, not a keyword, but always use it.asha.average()is reallyStudent.average(asha), which is why the method needs that first parameter.
Read more: the official tutorial's classes chapter.
Done here? The practice set for Part 9 โ 8 exercises with solutions โ is on the part page.