What are methods in python how are they different from functions?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function.

    Python Method

    1. Method is called by its name, but it is associated to an object (dependent).
    2. A method definition always includes ‘self’ as its first parameter.
    3. A method is implicitly passed the object on which it is invoked.
    4. It may or may not return any data.
    5. A method can operate on the data (instance variables) that is contained by the corresponding class

    Basic Method Structure in Python : 

    Python

    class class_name

        def method_name () :

            ......

            ......   

    Python 3 User-Defined Method : 

    Python3

    class ABC :

        def method_abc (self):

            print("I am in method_abc of ABC class. ")

    class_ref = ABC()

    class_ref.method_abc()

    Output:

     I am in method_abc of ABC class

    Python 3 Inbuilt method : 

    Python3

    import math

    ceil_val = math.ceil(15.25)

    print( "Ceiling value of 15.25 is : ", ceil_val) 

    Output:

    Ceiling value of 15.25 is :  16

    Know more about Python ceil() and floor() method.

    Functions

    1. Function is block of code that is also called by its name. (independent)
    2. The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly.
    3. It may or may not return any data.
    4. Function does not deal with Class and its instance concept.

    Basic Function Structure in Python : 

    Python3

    def function_name ( arg1, arg2, ...) :

        ......

        ......   

    Python 3 User-Defined Function : 

    Python3

    def Subtract (a, b):

        return (a-b)

    print( Subtract(10, 12) )

    print( Subtract(15, 6) )

    Output:

    -2
    9

    Python 3 Inbuilt Function : 

    Python3

    s = sum([5, 15, 2])

    print( s )

    mx = max(15, 6)

    print( mx )

    Output:

    22
    15

    Know more about Python sum() function. Know more about Python min() or max() function.

    Difference between method and function

    1. Simply, function and method both look similar as they perform in almost similar way, but the key difference is the concept of ‘Class and its Object‘.
    2. Functions can be called only by its name, as it is defined independently. But methods can’t be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class.

    A method is called by its name but it is associated with an object (dependent). It is implicitly passed to an object on which it is invoked. It may or may not return any data. A method can operate the data (instance variables) that is contained by the corresponding class.

    What does a method look like?

    Basic Python method

    class class_name
    	def method_name():
    	…………
    	# method body
    	…………

    Example of method

    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 is a method_meth of Meth class.
    

    Functions

    The function is a block of code that is also called by its name (independent). A function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly. It may or may not return any data. The function does not deal with class and its instance concept.

    How does a function look like?

    def function_name(arg1, arg2, ….):
    	…………..
    #function body
    …………..

    Rules for defining a function in Python

    • Function block should always begin with the keyword ‘def, followed by the function name and parentheses.
    • We can pass any number of parameters or arguments inside the parentheses.
    • The block of a code of every function should begin with a colon (:)
    • An optional ‘return’ statement to return a value from the function

    Example of function

    def Add (a,b):
        return(a+b)
     
    print(Add(50,70))
    print(Add(150,50))
    Output:
    120
    200
    
    

    Difference between Method and Function – Method vs. Function

    Function and method both look similar as they perform in an almost similar way, but the key difference is the concept of ‘Class and its Object’. Functions can be called only by its name, as it is defined independently. But methods cannot be called by its name only we need to invoke the class by reference of that class in which it is defined, that is, the method is defined within a class and hence they are dependent on that class.

    Functions in Python

    A function is an organized block of statements or reusable code that is used to perform a single/related action. Python programming three types of functions:

    • Built-in/library functions
    • User-defined functions
    • Anonymous functions

    Built-in functions in Python

    In total, there are 69 built-in functions in Python. They are:

    abs()
    delattr()
    hash()
    memoryview()
    set()
    all(
    dict()
    help()
    min()
    setattr()
    any()
    dir()
    hex()
    next()
    slice()
    ascii()
    divmod()
    id()
    object()
    sorted()
    bin()
    enumerate()
    input()
    oct()
    staticmethod()
    bool()
    eval()
    int()
    open()
    str()
    breakpoint()
    exec()
    isinstance()
    ord()
    sum()
    bytearray()
    filter()
    issubclass()
    pow()
    super()
    bytes()
    float()
    iter()
    print()
    tuple()
    callable()
    format()
    len()
    property()
    type()
    chr()
    frozenset()
    list()
    range()
    vars()
    classmethod()
    getattr()
    locals()
    repr()
    zip()
    compile()
    globals()
    map()
    reversed()
    __import__()
    complex()
    hasattr()
    max()
    round()

    User-defined functions in Python

    There are 4 steps in the construction of a user-defined function in Python:

    • Use the keyword “def” to declare a user-defined function following up the function name
    • Adding parameters to the function, and ending the line with a colon
    • Adding statements that the function should execute
    • Ending a function with a return statement if you want a function should output something. If you do not use the return statement, then the function will return an object “none”

    Example

    def hello():
      print("Hello World") 
      return 

    Anonymous functions in Python

    Anonymous functions in python cannot be declared in an ordinary manner which means they are not defined using the “def” keyword. These functions don’t have a body and are not required to call. Hence, they can be directly declared using the “lambda” keyword. It also helps in shortening the code. Lambda function can have n number of arguments but has a single return value that is represented in the form of expression. Lambda function does not need commands or multiple expressions. This kind of anonymous function cannot be called directly for the output. As a Python coder, you can initialize your own local namespace and the inline statements are equivalent to C/C++, the purpose of which is bypassing function stack allocation.

    Syntax

    lambda [arg1 [,arg2,.....argn]]:expression

    Example of Lambda function

    The below example will demonstrate how a basic function is different from Lambda.

    # normal function linear expression 
    def lin(x):
         return 3*x + 2
    print(lin(2))
    # lambda function
    f = lambda x: 3*x + 2
    print(f(2))
    Output
    8
    8
    

    The above example shows the presentation of a normal function and lambda function. As it can be clearly seen that giving logic in a normal function requires two steps but for anonymous functions, it can be represented in a single step.

    Calling a function in Python
    Calling a function means to execute a function that you have defined either directly from Python prompt or through another function (nested function).

    Example

    def greet(name):
        """
        This function greets to
        the person passed in as
        a parameter
        """
        print("Hello, " + name + ". Pythonists")
    greet('Codegnan')
    Output:
    Hello, Codegnan. Pythonists
    

    Function Arguments

    Python programming makes use of 4 types of function arguments:

    • Required argument
    • Keyword argument
    • Default argument
    • Variable-length argument

    Required argument
    These are the arguments that are passed in sequential order to a function. The only rule is that the number of arguments defined in a function should match with the function definition.

    Example:

    def addition(a, b):
           sum = a+b
           print("Sum after addition: ",sum)
     
    addition(5, 6)
    Output:
    Sum after addition:  11
    

    Keyword argument

    When the use of keyword arguments is done in a function call, the caller identifies the arguments by the argument name.

    Example:

    def language(lname):
           print(“We are learning a language called: ”, lname)
     
    language(lname = “Python”)
    Output:
    We are learning a language called: Python
    

    Default argument

    When a function is called without any arguments, then it uses the default argument.

    Example:

    def country(cName = “India”):
           print(“Current country is:”, cName)
     
    country(“New York”)
    country(“London”)
    country()
    Output:
    Current country is: New York
    Current country is: London
    Current country is: India
    

    Variable-length arguments

    If you want to process more arguments in a function than what you specified while defining a function, then these types of arguments can be used.
    Example:

    def add(*num): 
           sum = 0
           for n in num: 
                  sum = n+sum
           print(“Sum is:”, sum)
     
    add(2, 5)
    add(5, 3, 5)
    add(8, 78, 90)
    Output:
    Sum is: 7
    Sum is: 13
    Sum is: 176
    

    Time to implement – Function Exercises

    With this article, you have learned about functions in Python and the difference between methods and functions. Now, it’s time to get your hands dirty with some practical examples to introspect what you have learned until now!

    Write a python function that takes in a person’s name, and prints out a greeting. The greeting must be at least three lines, and the person’s name should come in each line. Use your function to greet at least three different people. [Tip: Save your three people in a list, and call your function from a for loop]

    Write a function that takes in a first name and the last name, and prints out a nicely formatted full name, in a sentence. Your sentence could be as simple as, “Hello, full_name.” Call your function three times, with a different name each time.
    Write a function that takes in two numbers, and adds them together. Make your function print out a sentence showing the two numbers, and the result. Call your function with three different sets of numbers.

    Modify Addition Calculator so that your function returns the sum of the two numbers. The printing should be outside of the function. I hope this article has helped you in learning the fundamentals of Python functions. I hope you are clear with the topic now, and soon I will come up with a few more blogs on python.

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

    Difference between Python Methods vs Functions Methods are associated with the objects of the class they belong to. Functions are not associated with any object. We can invoke a function just by its name. Functions operate on the data you pass to them as arguments.

    What is a method in Python?

    A method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on.

    What is the difference between functions and methods?

    A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.