Methods

Methods are functions that belong to a class.

Syntaxdef bark(self): ...

A method is a function defined inside a class. It describes what an object can do. Like __init__, every method takes self as its first parameter so it can access the object's own data.

Calling a method

Call it on an object with a dot: rex.bark(). Python passes the object in as self automatically.

Example

Example · python
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return f'{self.name} says Woof!'

rex = Dog('Rex')
print(rex.bark())

# Output:
# Rex says Woof!

When to use it

  • A BankAccount class exposes deposit() and withdraw() methods that update the balance attribute.
  • A Rectangle class provides area() and perimeter() methods calculated from width and height.
  • A Session class has a is_expired() method that compares the current time to the session start.

More examples

Instance method modifying state

Defines two methods that read and update the instance's balance, with a guard for overdraft.

Example · python
class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError('Insufficient funds')
        self.balance -= amount

acc = BankAccount(100)
acc.deposit(50)
acc.withdraw(30)
print(acc.balance)   # 120

Method returning a computed value

Shows two methods that compute and return values derived from instance attributes.

Example · python
class Rectangle:
    def __init__(self, w, h):
        self.w = w
        self.h = h

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

    def perimeter(self):
        return 2 * (self.w + self.h)

r = Rectangle(4, 6)
print(r.area())        # 24
print(r.perimeter())   # 20

Method calling another method

Shows describe() calling self.area() internally to compose a human-readable summary.

Example · python
class Circle:
    PI = 3.14159

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return self.PI * self.radius ** 2

    def describe(self):
        return f'Circle r={self.radius}, area={self.area():.2f}'

c = Circle(7)
print(c.describe())   # Circle r=7, area=153.94

Discussion

  • Be the first to comment on this lesson.