What are methods in python how are they different from functions?
View Discussion Show
Improve Article Save Article 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
Basic Method Structure in Python : Python
Python 3 User-Defined Method : Python3
Output: I am in method_abc of ABC class Python 3 Inbuilt method : Python3
Output: Ceiling value of 15.25 is : 16 Know more about Python ceil() and floor() method. Functions
Basic Function Structure in Python : Python3
Python 3 User-Defined Function : Python3
Output: -2 9 Python 3 Inbuilt Function :
Python3
Output: 22 15 Know more about Python sum() function. Know more about Python min() or max() function. Difference between method and function
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. Basic Python method Example of method 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. 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. 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 functions in PythonIn 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 PythonThere are 4 steps in the construction of a user-defined function in Python:
Example def hello(): print("Hello World") return Anonymous functions in PythonAnonymous 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 functionThe 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 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 ArgumentsPython programming makes use of 4 types of function arguments:
Required argument Example: def addition(a, b): sum = a+b print("Sum after addition: ",sum) addition(5, 6) Output: Sum after addition: 11 Keyword argumentWhen 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 argumentWhen 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 argumentsIf
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. 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 ExercisesWith 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. 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.
|