Method and Function are important things in any programming language.
Python Method
A method in Python is kindly similar to a function, except it is associated with objects/classes.
The method is accessible to data that is contained within the class so the class is compulsory for invoking the method. The method doesn’t have any return type. It creates an object of class for implementation.
Example:
Here we have defined the class XYZ, a method named method_xyz with “def” that prints the statement. After that, we called the defined method with “class_ref” via making it an object of the class XYZ.
class XYZ:
def method_xyz(self):
print("I am in method_xyz of XYZ class.")
class_ref = XYZ()
class_ref.method_xyz()
OUTPUT: I am in method_xyz of XYZ class.
In this example, we use the math library from Python to find the area of a circle. It directly fetches the value of pie and gives the result.
import math
radius = 4
area = math.pi * (radius ** 2)
print('The area of a circle is:',area)
OUTPUT: The area of a circle is: 50.26548245743669
Python Function
A function is a block of code that is also called by its name which means it is independent. Data is explicitly passed to a function.
It may or may not return any data and doesn’t deal with a class. Like a method, it also needs “def” for defining the function definition.
There are two types of functions in Python: User-defined and Built-in.
Example:
User-defined Function:
In this, we define add function for addition of two random numbers.
def add(a, b):
return a + b
print("add = ", add(3, 4))
OUTPUT: add = 7
Built-in Function:
In this, we use the library function of Python for performing an operation.
a = 5
b = 8
print(max(a,b))
print(type(a))
OUTPUT: 8 <class 'int'>
We have declared 2 variables (a, b) and are finding the maximum of the two using the max function. Next function (type) is showing the type of the variable.
Comments
0 comments
Article is closed for comments.