Concept
Methods: Functions Living Inside Objects
A method is a function defined inside a class that takes `self` as its first parameter to read or modify the instance's state.
python
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
acc = BankAccount(100)
print(acc.deposit(50)) # 150
# 119. Methods: Functions Living Inside Objects A method is a function defined inside a class that takes `self` as its first parameter to read or modify the instance's state: ```python class BankAccount: def __init__(self, balance): self.balance = balance def deposit(self, amount): self.balance += amount return self.balance acc = BankAccount(100) print(acc.deposit(50)) # 150 ``` When you invoke `acc.deposit(50)`, Python translates that syntax to `BankAccount.deposit(acc, 50)`. That is why the `self` parameter is mandatory in every method definition.
Checkpoint
Why must regular instance methods take `self` as their first parameter?
Practice
Create a class `Counter` initialized with `count = 0`. Add an `increment(self)` method that adds 1 to `self.count` and returns it. Call it twice on an instance and print the result.
01
Tap code blocks below to assemble
Available Blocks