Python OOP
Python Methods
A method is simply a function defined inside a class, and it always operates on a particular object through the self parameter.
Defining an Instance Method
Methods are indented inside the class body, just like __init__. The first parameter is always self, which represents the object the method was called on.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def show_balance(self):
print(f"{self.owner}'s balance: {self.balance}")Calling Methods
You call a method on an object using dot notation. Python automatically passes the object as self, so you only supply the remaining arguments.
acc = BankAccount("Sara", 1000)
acc.deposit(500)
acc.show_balance()Sara's balance: 1500Method vs Function
A regular function is independent and lives at the module level; a method belongs to a class and is called through an object, always receiving that object as its first argument automatically.
| Function | Method |
|---|---|
| Defined outside a class | Defined inside a class |
| Called directly: greet() | Called on an object: obj.greet() |
| No automatic self | Receives self automatically |
| Not tied to any data | Operates on an object's attributes |
Behind the scenes, obj.method(x) is equivalent to ClassName.method(obj, x) — Python just writes the friendlier dot-notation version for you.
Instance methods are the most common kind of method; Python also has class methods and static methods, covered in a later topic.
