
1. Function
A function is a standalone block of code designed to perform a specific task. It can be called independently and usually takes inputs (arguments) and returns a result.
Characteristics of a Function:
- Standalone: Functions are not bound to any object or class.
- Input: Functions can take arguments.
- Output: They often return a value.
- Global Scope: Functions can be called from anywhere in the code (depending on their scope).
Example in Python:
# A simple function
def greet(name):
return f"Hello, {name}!"
# Calling the function
print(greet("Alice")) # Output: Hello, Alice!
Here, greet() is a function. It is independent of any object and can be called with different arguments to perform its task.
2. Method
A method is a function associated with an object or a class. It operates on the data (attributes) within the object and is designed to work with the object it is called on.
Characteristics of a Method:
- Associated with a Class or Object: Methods are defined within a class and are called on an instance of that class.
- Access to Object Data: Methods can access and modify the object’s attributes.
- Requires an Object: A method we can use as an instance of the class (except for class methods (or) static methods).
Example in Python:
# Define a class with a method
class Person:
def __init__(self, name):
self.name = name
# This is a method
def greet(self):
return f"Hello, {self.name}!"
# Creating an object (instance) of the class
person = Person("Alice")
# Calling the method on the object
print(person.greet()) # Output: Hello, Alice!
Here, greet() is a method because it is defined inside the class Person and is called on an instance of the class (person). It has access to the instance’s name attribute.
Key Differences:
| Aspect | Function | Method |
|---|---|---|
| Definition | Independent block of code | Defined within a class |
| Association | Not associated with any object or class | Associated with an object or class |
| Called On | Can be called directly | Called on an instance (object) of a class |
| Access to Data | Cannot access class/instance data directly | Can access and modify the object’s data |
| Usage | function_name() | object.method_name() |
Example in Python: Function vs Method
# Function
def multiply(a, b):
return a * b
# Class with a method
class Calculator:
def __init__(self, value):
self.value = value
def multiply_by(self, num):
return self.value * num
# Calling a function
print(multiply(3, 4)) # Output: 12
# Using a method
calc = Calculator(10)
print(calc.multiply_by(4)) # Output: 40
multiply()is a function and can be called directly.multiply_by()is a method because it is part of theCalculatorclass and must be called on an instance of the class (calc).
Summary:
- A function is a self-contained piece of code that can be called independently.
- A method is a function that is part of a class and is invoked on an instance (object) of that class.
References







You must be logged in to post a comment.