Python Methods vs Functions

We have only methods in Java and only functions in C but in Python, we have both functions and methods. They look and work alike and this raises a lot of doubts for newbies and mainly for programmers coming from Java and C.

In this article, we aim to discuss the differences between Methods and Functions and get a clear picture of both.

Functions in Python

A function is a collection of lines of code that accomplishes a certain task. Functions have:

  • Name
  • Parameters
  • Return statement

Return statement and parameters are optional. A function can either have them or not.

Creating a function in Python

We can create a function using the keyword def.
Syntax

def function_name(parameters):
    # Statements...

Example of how to create Function in Python

def join(str1, str2):
    joined_str = str1 + str2
    return joined_str
print(join)

Output

<function join at 0x10ec5c280>

In the above code example, we created a function named join which combines its two parameters and returns a concatenated string.

Functions are only executed when they are called.

Calling a function in Python

Without calling, a function will never run. To call a function we use the following syntax

Syntax

function_name(arguments)

Example of how to call Function in Python

print(join("Python", "Geeks"))

Output

PythonGeeks

In the above code example, we executed our function join() by calling it with two arguments “Python” and “Geeks” and it returned their concatenated string “PythonGeeks”.

Types of Functions in Python

1. Built-in Functions in Python

Functions that are already pre-defined in the Python built-in modules are called Built-in Functions. Since they are already defined, we don’t need to create them. Python consists of several built-in functions. To use these functions, we just need to call them.

For Example

li = [1,2,3]
ans = sum(li)
print(ans)

Output

6

In the above code example, we used two Built-in functions, sum() and print() to find and output the sum of the list li.

2. User Defined Functions (UDFs) in Python

Functions that users define are called User Defined Functions. UDF is the acronym for User Defined Function. To use these functions, we first need to define them and call them. We can define as many UDFs as we need in our program.

For Example

def add(num1, num2):
    sum = num1 + num2
    return add
print(add(1,2))

Output

3

In the above code example, we defined our own function add(). This is called a User Defined Function. Then we called it with arguments 1 and 2 to return their sum 3.

3. Anonymous Functions in Python

Functions without a name and are declared without using the keyword def are called Anonymous Functions. To create these functions, we use the keyword lambda and these functions are also called Lambda Functions.

For Example

li = [1,2,3]
new = list(map(lambda x:x+1, li))
print(new)

Output

[2, 3, 4]

In the above code example, we used the lambda function to increment every value in the list.

Methods in Python

Functions inside a class are called methods. Methods are associated with a class/object.

Creating a method in Python

We use the same syntax as function but this time, it should be inside a class.

Syntax

class ClassName:
def method_name(parameters):
    # Statements…

For Example

class Addition:

def add(self, num1, num2):
    return num1 + num2
print(Addition.add)

Output

<function Addition.add at 0x1088655e0>

Calling a Method in python

To use a method, we need to call it. We call the method just like a function but since methods are associated with class/object, we need to use a class/object name and a dot operator to call it.

Syntax

object_name.method_name(arguments)

For Example

addition1 = Addition() # Object Instantiation
print(addition1.add(2, 3))

Output

5

In the above code example, we created an object addition1 for our class Addition and used that object to call our method add() with arguments 2 and 3. After calling, our method got executed and returned the value 5.

Being inside a class gives methods a few more abilities. Methods can access the class/object attributes. Since methods can access the class/object attributes, they can also alter them.

Methods vs Functions in Python

Functions in Python Methods in Python
Functions are outside a class Methods are created inside a class
Functions are not linked to anything Methods are linked with the classes they are created in
Functions can be executed just by calling with its name To execute methods, we need to use either an object name or class name and a dot operator.
Functions can have zero parameters. Methods should have a default parameter either self or cls to get the object’s or class’s address.
Functions can not access or modify class attributes Methods can access and modify class attributes
Functions are independent of classes Methods are dependent on classes

By looking at the above differences, we can simply say that all methods are functions but all functions are not methods.

Interview Questions on Methods vs Functions in Python

Q1. From the given code, write the output and identify which are functions and which are methods.

class vegetables:

    def __init__(self, name):
        self.name = name
        self.veggies_eaten = 0

    def eat_one(self):
        self.veggies_eaten += 1
        return f"Eaten one {self.name}"

v1 = vegetables("Radish")
v2 = vegetables("Beetroot")

def eat_many(vegetable, count):

    for i in range(count):
        vegetable.eat_one()

eat_many(v1, 20)
eat_many(v2, 1)

print(v1.veggies_eaten)
print(v2.veggies_eaten)

Ans 1. Output is as follows:

20
1Functions:
eat_many(vegetables, count)Methods:
__init__(self, name)
eat_one(self)

Q2. Create a method is_empty() that returns “Yes” if it is an empty list or “No” if it is not an empty list.

Ans 2. Code is as follows:

class Checker:

    def __init__(self, list1):
        self.list1 = list1

    def is_empty(self):
        if self.list1:
            return "No"
        return "Yes"

Q3. Create a function that takes an argument number and returns the square root of the tenth power of that number.

Ans 3. Code is as follows:

from math import sqrt

def square_root(num):
    power = pow(num, 10)
    return sqrt(power)

Q4. Create a function that takes an argument n and creates n objects of class Employee.

Ans 4. Code is as follows:

class Employee:

    def __init__(self, emp_id):
        self.emp_id = emp_id

def create_employees(n):

    employee_list = []

    for i in range(n):
        employee_list.append(Employee(i))

Q5. The below code raises a NameError. Correct the code and explain why it raised an error.

class Polygons:

    def __init__(self, edges):
        self.edges = edges

    def get_edges(self):
        return self.edges

p1 = Polygons(4)

print(get_edges())

Ans 5. NameError occurs because the method is called without using the object name. The corrected code is:

class Polygons:

    def __init__(self, edges):
        self.edges = edges

    def get_edges(self):
        return self.edges

p1 = Polygons(4)

print(p1.get_edges())

Output

4

Python Methods vs Functions Quiz

Conclusion

In this article, we have discussed the differences between functions and methods. Furthermore, If you have any queries, please feel free to share them with us in the comment section.

If you are Happy with PythonGeeks, do not forget to make us happy with your positive feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *