Since I am always confused with methods and function, I did some reading about them and here is what I understand.
- methods and functions look the same
- they both have parenthesis()
- they can both take argument
- When defining, they both have
defbefore the name
- Methods cannot call on its own, it need an object to call with, functions can call on it own.
- Methods need and dot.operator, functions do not
- Methods must be defined within a class, function can define on its own
- 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?
class Car: def make_sound(self): print "Bloom!" ferrari = Car() ferrari.make_sound()
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.
def car_make_sound(): print("Bloom!") car_make_sound()
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.