Methods

A method is a function that belongs to a class. Methods can read and modify the object's own data using self, and they define the behaviour of an object.

Defining an Instance Method

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

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

c = Circle(5)
print(c.area())  # → 78.53975
78.53975
  • Methods are defined inside the class body, indented one level
  • self is always the first parameter — Python passes the object automatically
  • Call a method with object.method() — you do not pass self yourself

Methods with Parameters

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

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

account = BankAccount(100)
account.deposit(50)
print(account.balance)  # → 150
150

Multiple Methods in One Class

class Rectangle:
    def __init__(self, width, height):
        self.width  = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

Your Task

  1. Write an area method inside Rectangle that returns self.width * self.height
  2. Write a perimeter method that returns 2 * (self.width + self.height)
  3. Test: Rectangle(4, 5).area() should return 20 and Rectangle(4, 5).perimeter() should return 18
Section 1/4Defining an Instance Method

Defining an Instance Method

Explore this concept

Methods

A method is a function that belongs to a class. Methods can read and modify the object's own data using self, and they define the behaviour of an object.

Defining an Instance Method

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

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

c = Circle(5)
print(c.area())  # → 78.53975
78.53975
  • Methods are defined inside the class body, indented one level
  • self is always the first parameter — Python passes the object automatically
  • Call a method with object.method() — you do not pass self yourself

Output:

Click "Check" to run your code.