Sobes.tech
Middle

Do you know the difference between a method and a function in Python?

sobes.tech AI

Answer from AI

In Python, a function is a block of code that can be called by name and can accept arguments and return values. A method is a function that is associated with an object (usually an instance of a class) and is called through that object.

The main difference is that a method is always called through an object and automatically receives a reference to that object (usually the self parameter), whereas a function is not tied to an object and is called independently.

Example:

class MyClass:
    def method(self):
        print("This is a method associated with an object", self)

def function():
    print("This is a regular function")

obj = MyClass()
obj.method()  # calling the method
function()    # calling the function
Do you know the difference between a method and a… - sobes.tech