Data with behaviour
Everything in Python is an object — numbers, strings, lists, even functions. Each has a type and methods: "momo".upper(), items.append(x). A class lets you define your own types: a bank account that knows its balance and refuses to go below zero, an order item that can total itself.
Python's classes are simpler than Java's or C#'s: no private, no new, no interfaces required. A leading underscore (_balance) is the convention for "internal, please don't touch". And for classes that mainly hold data, the @dataclass decorator writes the boring parts for you.
class, __init__ and self
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def __repr__(self):
return f"Account({self.owner!r}, {self.balance})"
acct = Account("Asha")
acct.deposit(500)
print(acct, acct.balance)self is just the conventional name for the first parameter of a method: the instance it was called on. acct.deposit(500) is really Account.deposit(acct, 500). Methods named with double underscores on both sides — a dunder method — are hooks Python calls for you: __init__ on creation, __repr__ for printing, __eq__ for ==, __len__ for len().