Methods vs Functions in Python
This article will dive into the differences between methods and functions in Python.
What are the functions in Python?
The main difference between method and function is:
The function is a standalone piece of the code in contrast a method belongs to an object.
The functions do not deal with the Class and its instance concept. We can call functions by their names.
There are two types of functions. Built-in and user-defined functions.
Let's look at a simple example:
def say_hi(name):
return f"Hi {name}"
print(say_hi("Alex"))In the above code, we defined a say_hi() function which accepts a name as a parameter. Then return the greeting message. The function may or may not return data.
What are the methods in Python?
Methods are similar to functions. A method is a function that belongs to an object. Methods are defined inside the class definition and they can only be called on instances of that class. Also, methods are able to change the internal state of the classes.
Get Sevdimali’s stories in your inbox
Join Medium for free to get updates from this writer.
We call methods by using dot notation, eg: object.method()
Let’s look at an example of the methods.
class Greeting:
def __init__(self, name):
self.name = name
def say_hi(self):
return f"Hi, {self.name}"
def say_hello(self):
return f"Hello, {self.name}"
greeting = Greeting(name="Alex")
print(greeting.say_hi())
print(greeting.say_hello())In the above code, we defined two methods inside our Greeting class.
In this example, the Greeting class has a constructor that takes a name parameter and sets the name instance variable. The say_hi and say_hello methods return different greetings that include the name instance variable.
Thanks for reading. I hope you enjoyed it ❤. If you found the article useful don’t forget to clap and follow me.
This is my #9/52 story in 2023, I’m on a challenge to write 52 stories in 2023.
Keep Learning..!










