
Python
Methods are functions that belong to a class and define what an object can do. Every method receives `self` as its first parameter, which represents the specific object calling that method. Understanding methods and self is crucial for writing effective object-oriented code.
Methods are functions defined inside a class that perform actions or retrieve information about an object. They can access and modify the object's attributes using `self`. Methods are the verbs of your class—they describe what objects of that class can do.
class Light:
def __init__(self, color):
self.color = color
self.is_on = False
# A method that performs an action
def turn_on(self):
self.is_on = True
return f"The {self.color} light is now ON"
# A method that retrieves information
def get_status(self):
status = "ON" if self.is_on else "OFF"
return f"Light is {status}"
# Create and use
light = Light("blue")
print(light.turn_on()) # Output: The blue light is now ON
print(light.get_status()) # Output: Light is ON`self` represents the specific object that a method is being called on. When you write `object.method()`, Python automatically passes the object as the first argument to the method. This is why every method definition includes `self` as the first parameter.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def fahrenheit(self):
# 'self' refers to this specific object
return (self.celsius * 9/5) + 32
def get_reading(self):
# Use 'self' to access this object's attributes
return f"Celsius: {self.celsius}, Fahrenheit: {self.fahrenheit()}"
# Create objects
temp1 = Temperature(0)
temp2 = Temperature(100)
# When you call a method, 'self' is automatically the object
print(temp1.get_reading()) # self is temp1
# Output: Celsius: 0, Fahrenheit: 32
print(temp2.get_reading()) # self is temp2
# Output: Celsius: 100, Fahrenheit: 212Instance methods are the most common—they work with instance attributes. They have `self` as the first parameter. Instance methods can read and modify the object's state.
class TodoList:
def __init__(self):
self.tasks = []
# Instance method - no parameters besides self
def get_count(self):
return len(self.tasks)
# Instance method - takes additional parameters
def add_task(self, task):
self.tasks.append(task)
return f"Added: {task}"
# Instance method - modifies the object
def remove_task(self, task):
if task in self.tasks:
self.tasks.remove(task)
return f"Removed: {task}"
return f"Task not found: {task}"
# Instance method - returns information
def list_tasks(self):
return f"Tasks ({self.get_count()}): {', '.join(self.tasks)}"
# Use the class
todo = TodoList()
print(todo.add_task("Study Python"))
print(todo.add_task("Exercise"))
print(todo.list_tasks())
print(todo.remove_task("Study Python"))
print(todo.list_tasks())Methods can accept additional parameters beyond `self`. These parameters are specified after `self` in the method definition. When you call the method, you provide values for these parameters.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
# No additional parameters
return self.width * self.height
def scale(self, factor):
# One additional parameter
self.width *= factor
self.height *= factor
return f"Scaled by {factor}x"
def compare(self, other):
# One additional parameter (another object)
return self.area() > other.area()
def resize(self, new_width, new_height):
# Multiple additional parameters
self.width = new_width
self.height = new_height
return f"Resized to {new_width}x{new_height}"
# Create and use
rect1 = Rectangle(5, 4)
rect2 = Rectangle(3, 3)
print(f"Area: {rect1.area()}") # Area: 20
print(rect1.scale(2)) # Scaled by 2x
print(f"New area: {rect1.area()}") # New area: 80
print(f"rect1 bigger? {rect1.compare(rect2)}") # True
print(rect1.resize(6, 3)) # Resized to 6x3Methods can change the object's attributes, modifying its state. This is one of the key powers of OOP—objects can track their own state and change it through methods.
class BankAccount:
def __init__(self, owner, initial_balance):
self.owner = owner
self.balance = initial_balance
self.transactions = []
def deposit(self, amount):
self.balance += amount
self.transactions.append(f"+${amount}")
return f"Deposited ${amount}. Balance: ${self.balance}"
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
self.transactions.append(f"-${amount}")
return f"Withdrew ${amount}. Balance: ${self.balance}"
else:
return "Insufficient funds"
def get_balance(self):
return f"Balance: ${self.balance}"
def get_history(self):
return f"Transaction history: {', '.join(self.transactions)}"
# Use the class
account = BankAccount("Alice", 1000)
print(account.deposit(500))
print(account.withdraw(200))
print(account.get_balance())
print(account.get_history())class Portfolio:
def __init__(self, owner):
self.owner = owner
self.stocks = {}
def buy_stock(self, ticker, shares, price):
if ticker not in self.stocks:
self.stocks[ticker] = {"shares": 0, "total_cost": 0}
self.stocks[ticker]["shares"] += shares
self.stocks[ticker]["total_cost"] += shares * price
return f"Bought {shares} shares of {ticker}"
def get_value(self, current_prices):
total = 0
for ticker, data in self.stocks.items():
total += data["shares"] * current_prices.get(ticker, 0)
return total
def portfolio_summary(self):
return f"{self.owner} owns: {list(self.stocks.keys())}"
portfolio = Portfolio("Bob")
print(portfolio.buy_stock("AAPL", 10, 150))
print(portfolio.buy_stock("GOOGL", 5, 2800))
print(portfolio.portfolio_summary())
values = {"AAPL": 160, "GOOGL": 2850}
print(f"Total value: ${portfolio.get_value(values)}")class Timer:
def __init__(self, name):
self.name = name
self.elapsed = 0
self.running = False
def start(self):
if not self.running:
self.running = True
return f"{self.name} started"
return f"{self.name} is already running"
def stop(self):
if self.running:
self.running = False
return f"{self.name} stopped at {self.elapsed}s"
return f"{self.name} is not running"
def add_time(self, seconds):
if self.running:
self.elapsed += seconds
def reset(self):
self.elapsed = 0
self.running = False
return "Timer reset"
def get_time(self):
return f"{self.name}: {self.elapsed} seconds"
timer = Timer("Workout")
print(timer.start())
timer.add_time(30)
print(timer.get_time())
timer.add_time(20)
print(timer.stop())
print(timer.get_time())| Concept | Remember |
|---|---|
| Method | A function that belongs to a class and defines behavior |
| self | Represents the object instance calling the method |
| Instance Method | A method that works with instance attributes using self |
| Method Call | object.method() automatically passes object as self |
| Parameters | Methods can accept additional parameters after self |
| State Changes | Methods can modify object attributes to change state |
| Return Values | Methods can return results or just perform actions |
Now let's explore instance variables and how objects store and manage data.
Ready to practice? Try challenges or explore more concepts
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward