Skip to content

Module 11 · Object-Oriented Programming — topic 5 of 25

Methods

Functions defined inside a class: how self is passed automatically, calling methods on objects, methods that change state versus methods that compute values, and method chaining.

Beginner 10 min read·Lesson 162 of 306 in Python Programming

Learning objectives

  • Define and call methods
  • Explain how obj.method() becomes Class.method(obj)
  • Write query methods, command methods and chainable methods

Definition

A method is a function defined in a class body. When called through an instance (obj.method(args)), Python passes the instance automatically as the first argument, conventionally named self.

Introduction

acc.deposit(500) looks like a function call with one argument, but deposit receives two: the account itself and 500. That automatic first argument is what makes a function a method.

Why it matters

Methods put behaviour next to the data it uses. Callers don't need to know how a balance is stored; they just call deposit().

Detailed explanation

Methods are defined with def inside the class; their first parameter is self.

obj.method(a, b) is translated to Class.method(obj, a, b). obj.method without parentheses is a bound method object that remembers obj.

Query methods return information without changing the object (is_empty, total). Command methods change the object's state (add_item, clear). Keeping the two kinds separate makes code easier to reason about.

A method can call other methods of the same object with self.other_method().

Command methods can return self to allow chaining: cart.add('pen').add('book').

Syntax

Python
class Cart:
def __init__(self):
self.items = {}
def add(self, item, qty=1): # command
self.items[item] = self.items.get(item, 0) + qty
return self # enables chaining
def count(self): # query
return sum(self.items.values())
  • First parameter is self.
  • obj.m() passes obj as self.
  • Return self to chain.

Code examples

Calling methods

Python
class Rectangle:
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
def scale(self, factor):
self.w *= factor
self.h *= factor
r = Rectangle(2, 3)
print(r.area())
r.scale(2)
print(r.area(), Rectangle.area(r))
Output
6
24 24

Bound methods

Python
class Greeter:
def __init__(self, name):
self.name = name
def hello(self):
return f"Hello from {self.name}"
g = Greeter("Asha")
f = g.hello # a bound method remembers g
print(f())
print(type(f).__name__)
Output
Hello from Asha
method

More examples

Queries, commands and chaining

Python
class Cart:
PRICES = {"pen": 20, "book": 350, "bag": 1200}
def __init__(self):
self.items = {}
def add(self, item, qty=1):
if item not in self.PRICES:
raise KeyError(f"unknown item {item}")
self.items[item] = self.items.get(item, 0) + qty
return self
def remove(self, item):
self.items.pop(item, None)
return self
def count(self):
return sum(self.items.values())
def total(self):
return sum(self.PRICES[i] * q for i, q in self.items.items())
def summary(self):
return f"{self.count()} item(s), Rs {self.total()}"
cart = Cart().add("pen", 3).add("book").add("bag").remove("bag")
print(cart.items)
print(cart.summary())
Output
{'pen': 3, 'book': 1}
4 item(s), Rs 410

Step-by-step explanation

  • add and remove change the cart and return self, so calls can be chained on one line.
  • count and total only compute values — they never change the cart.
  • summary calls other methods through self.
  • The chain adds three item types and removes the bag.

Expected output

Running “Queries, commands and chaining” prints exactly:

TextOutput
{'pen': 3, 'book': 1}
4 item(s), Rs 410

Practical applications

  • String methods are query methods: they return new strings.
  • Builder-style APIs (query builders, plot configuration) chain command methods.

Best practices

  • Name methods with verbs; queries can be nouns or is_/has_ names.
  • Keep query methods free of side effects.
  • Return self from command methods only when chaining helps.

Common mistakes

Forgetting self in the definition

Avoid

class A:
def show():
print("hi")
A().show() # TypeError

Prefer

class A:
def show(self):
print("hi")

Python passes the instance automatically, so the method must accept it.

Forgetting self. when using attributes

Avoid

def area(self):
return w * h # NameError

Prefer

def area(self):
return self.w * self.h

Attributes are reached through self.

Important notes

  • list.append returns None rather than self — Python's built-ins usually avoid chaining for mutating methods.

Key takeaways

  • Methods are functions in a class; self is passed automatically.
  • obj.m(x) is Class.m(obj, x).
  • Separate queries from commands.

Try it yourself

  1. 1
    Add deposit, withdraw and statement methods to an Account class.
  2. 2
    Make a TextBuilder class whose methods return self so you can chain add_line calls.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module