DEV Community

pagarsach14
pagarsach14

Posted on

difference between function and Method in python

what is function:
A function is a block of code to carry out a specific task, will contain its own scope and is called by name. All functions may contain zero(no) arguments or more than one arguments. On exit, a function can or can not return one or more values.

Basic function syntax
def functionName( arg1, arg2,….):
…….

Function_body

……..
Let’s create our own (user), a very simple function called sum(user can give any name he wants)”. Function “sum” is having two arguments called num1 and num2 and will return the sum of the arguments passed to the functionsum). When we call the function (sum) with values(arguments) 5 and 6, it returns 11.
def sum(num1, num2):
return (num1 + num2)

Output

sum(5,6)
11

what is Method:
A method in python is somewhat similar to a function, except it is associated with object/classes. Methods in python are very similar to functions except for two major differences.

The method is implicitly used for an object for which it is called.python

The method is accessible to data that is contained within the class.book

General Method Syntax
class ClassName:
def methodname(): ………….. # Methodbody
………………
class Pet(object):
def mymethod(self): print("I am a Cat") cat = Pet() cat.mymethod()
Output
I am a Cat
for detailed information see python books
Reference: https://www.pythonslearning.com/2020/07/method-vs-function-python.html
BEST OF LUCK!!

Top comments (0)