What is a method?
Think of an object as a person in a restaurant: they have data (their order) and behaviour (how to pay). A method is the action part. It lets your class do something instead of just sitting there holding values.
class CoffeeOrder:
def __init__(self, drink):
self.drink = drink
self.size = 'medium'
def add_syrup(self):
print(f'Adding syrup to {self.drink}')
order = CoffeeOrder('latte')
order.add_syrup()add_syrup is a method. It lives inside the class and knows about self. You call it on a specific object, and it works with that order's own data.The self parameter
Every method starts with
self. This word means this specific instance. When two objects of the same class exist, each has its own data. self is how the code knows whose data to touch.class BankAccount:
def __init__(self, owner):
self.owner = owner
self.balance = 0.0
def deposit(self, amount):
self.balance += amount
tom = BankAccount('Tom')
sara = BankAccount('Sara')
tom.deposit(120)
sara.deposit(45)
print(f"{tom.owner}: {tom.balance}") # Tom: 120.0
print(f"{sara.owner}: {sara.balance}" )# Sara: 45.0deposit changes self.balance. Because each account has its own storage, depositing to one does not affect the other.Methods that return values
class Invoice:
def __init__(self, item, price):
self.item = item
self.price = price
def apply_discount(self, percent):
discount = self.price * (percent / 100)
return self.price - discount
bill = Invoice('notebook', 25.00)
cost = bill.apply_discount(10)
print(cost) # 22.5apply_discount reads self.price, does the math, and returns a new number. The original object is unchanged unless you explicitly assign to an attribute.Changing state inside methods
class Task:
def __init__(self, title):
self.title = title
self.done = False
def complete(self):
self.done = True
task = Task('write report')
print(task.done) # False
task.complete()
print(task.done) # Truecomplete() flips self.done. This is how objects remember state over time. Your exercises will use this pattern: methods that read, calculate, or update the data stored on each instance.