Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 09 / Topic 2 of 12

Class and object, __init__, self

  • class Name: defines a class. Class names use PascalCase (BankAccount, not bank_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).
  • self is the object being set up or used. Python passes it in for you; you never pass it yourself.
  • self.name = name creates 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: self is only a habit, not a keyword, but always use it. asha.average() is really Student.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.

Search the guide