Let’s understand the difference between Python methods and functions and when and how to use function or method:
Functions:
- Functions are standalone blocks of code that can be called by their name.
- They are defined independently and are not associated with any specific class or object.
- Functions can have zero or more parameters.
- They may or may not return any data.
- Example of a user-defined function:
def subtract(a, b): return a - b print(subtract(10, 12)) # Output: -2
Methods:
- Methods are special types of functions associated with a specific class or object.
- They are defined within a class and are dependent on that class.
- A method always includes a
self
parameter (for instance methods) or acls
parameter (for class methods). - Methods operate on the data (instance variables) contained by the corresponding class.
- Example of a user-defined method:
class ABC: def method_abc(self): print("I am in method_abc of ABC class.") class_ref = ABC() # Create an object of ABC class class_ref.method_abc() # Output: "I am in method_abc of ABC class."
In final conclusion, functions are independent, while methods are associated with classes or objects. Functions can be called directly by their name, but methods require invoking the class or object they belong to.
No comments:
Post a Comment