Python Classes and Objects: __init__, self, Inheritance
A class defines a new type of object that bundles data (attributes) with the functions that work on it (methods). BankAccount in the example describes what every account has, an owner and a balance, and what it can do, accept deposits. Each account you create from it is an instance.
init and self
__init__ runs automatically when you create an instance with BankAccount("Ava", 100). Its job is to set up the instance's attributes. The first parameter of every method is the instance itself, conventionally named self. Python passes it for you: a.deposit(25) becomes BankAccount.deposit(a, 25) behind the scenes. Inside a method, self.balance reads or changes that particular account's balance.
Instance and class attributes
Attributes assigned through self belong to one instance. A variable written directly in the class body, like bank = "TetBank", is a class attribute shared by all instances. Use class attributes for constants; putting a mutable list there would share it between every instance.
Special methods
Methods with double underscores on both sides, called dunder methods, hook into Python's built-in behavior. __repr__ returns the text shown when you print the object or inspect it in a shell. Without it you get something like <__main__.BankAccount object at 0x10d...>. Others include __len__, __eq__ and __str__.
Expected output
BankAccount('Ava', 125) TetBank
210.0
True SavingsAccountInheritance
class SavingsAccount(BankAccount): creates a subclass. It inherits every attribute and method of BankAccount and adds add_interest. Inside that new method, self.deposit(...) calls the inherited method. A subclass can also override a method by defining one with the same name; inside it, super().method() calls the parent version. isinstance(s, BankAccount) is True because a savings account is also a bank account.
When to write a class
Write a class when several functions keep passing the same group of data around, or when you need many objects of the same shape. For a plain record with no behavior, the dataclasses module removes most of the boilerplate, generating __init__ and __repr__ for you.
Common mistakes
- Forgetting
selfas the first parameter, which givesTypeError: ... takes 1 positional argument but 2 were given. - Writing
balance = 0inside a method instead ofself.balance = 0, which only creates a local variable. - Calling
BankAccount.deposit(25)on the class instead of on an instance.
Summary
class Name:defines a type; callingName(...)creates an instance and runs__init__.selfis the instance;self.xattributes belong to it.- Dunder methods such as
__repr__customize built-in behavior. - Subclasses inherit and can extend or override parent methods.
Quiz: Classes and objects