DEV Community 👩‍💻👨‍💻


Posted on • Updated on

Python Concept learning point 1: Difference between methods and functions

Since I am always confused with methods and function, I did some reading about them and here is what I understand.

What confused me

  • methods and functions look the same
  • they both have parenthesis()
  • they can both take argument
  • When defining, they both have def before the name

The difference between methods and functions

  1. Methods cannot call on its own, it need an object to call with, functions can call on it own.
  2. Methods need and dot.operator, functions do not
  3. Methods must be defined within a class, function can define on its own
  4. When defining, methods require at least one parameter, and the first must be self, function can have any number of parameter(including 0)

The follow two program will have an output of "Bloom", but whats the difference?

Example 1: method

class Car:
    def make_sound(self):
        print "Bloom!"

ferrari = Car()
Enter fullscreen mode Exit fullscreen mode

Take make_sound as example, make_sound is define within a class, it takes self as its first parameter, it has a dot before it, so it is a method.

Example 2: function

def car_make_sound():

Enter fullscreen mode Exit fullscreen mode

This time car_make_sound() is a function, although it also has an output of Bloom!. But it does not have class on top, it does not have any parameter and it have not object and . operator before it.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.