Account
Categories
Shobha
Shobha
The best way to predict the future is to invent it

What is the difference between a function and a method in Python?

A function is a block of reusable code defined using the def keyword that performs a specific task. It is called independently and can exist globally or within another function.Functions are standalone and don’t depend on objects.
Example:

def greet(name):
return f"Hello, {name}!"
print(greet("John"))
A method, on the other hand, is a function associated with an object. It is called on an instance of a class and can access or modify the object’s attributes. Methods implicitly pass the instance (self) as their first argument.Methods are tied to objects and can access their state
Example:

class Person:
def greet(self):
print("Hello, I am a method.")
p = Person()
p.greet() # Calling the method using the instance of the class