Today’s Data Hack is a helpful reminder of the difference between methods and functions in Python and when to use them. Let’s begin with methods:
While a method is called by its name, it is still associated with an object (dependent). This may or may not return data. Another important feature is that a method can operate data contained by the corresponding class. Here is an example:
Basic Python
class class_name
def method_name():
…………
# method body
…………
Method class
class Meth:
def method_meth (self):
print (“This is a method_meth of Meth class.”)
class_ref = Meth() #object of Meth class
class_ref.method_meth()
This differs from functions, which are blocks called by their name (independents). A function can have different parameters and if any data is passed, then it is done quickly. The function, however, does not interact with class. Here is an example:
def function_name(arg1, arg2, …):
#function body
In other words, methods and functions look similar but the central difference is in “Class and its Object.” A function can only be called by its name and is defined independently. For a method, you must invoke the class by reference of the class in which it is defined.