Methods
Give your objects actions.
🎬 Video version coming soon — read it now
A method is a function defined inside a class. It works on the object's own data through self.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks # a list of marks
def average(self):
return sum(self.marks) / len(self.marks)
def has_passed(self, pass_mark=35):
return all(m >= pass_mark for m in self.marks)
def add_mark(self, mark):
self.marks.append(mark)
s = Student("Divya", [88, 94, 79])
print(f"{s.average():.1f}") # 87.0
s.add_mark(91)
print(s.has_passed()) # TrueEvery method takes self first. When you call s.average(), Python passes s as self for you.
Methods that change the object vs methods that answer questions
add_markchanges the object's stateaverageandhas_passedanswer a question and return a value without changing anything
Keeping those two kinds separate makes code easier to reason about.
Methods calling methods
class Student:
# ... __init__, average and has_passed as above ...
def grade(self):
avg = self.average()
if avg >= 90:
return "A+"
if avg >= 75:
return "A"
return "B"
def report(self):
status = "Pass" if self.has_passed() else "Fail"
return f"{self.name}: {self.average():.1f} ({self.grade()}) {status}"Use self. to reach other methods and attributes of the same object.
Example: a shopping cart
class Cart:
def __init__(self):
self.items = {} # name -> (price, qty)
def add(self, name, price, qty=1):
_, old_qty = self.items.get(name, (price, 0))
self.items[name] = (price, old_qty + qty)
def total(self):
return sum(price * qty for price, qty in self.items.values())
cart = Cart()
cart.add("Notebook", 60, 3)
cart.add("Pen", 10, 5)
cart.add("Pen", 10, 2)
print(cart.total()) # 250Tip: If a function's first parameter is always the same kind of object, like
def deposit(account, amount), it probably wants to be a method of that class.In one line
Methods are functions inside a class that use self to read and change the object's own data.
Saved on this device. Sign in to keep progress everywhere.
Share with a friend