Python/Definitions
< Python
Jump to navigation
Jump to search
Function vs Method
method is the object-oriented word for function, no real difference. So, the split is:
- method is on an object.
- function is independent of an object.
- A function
- is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.
- A method
- is a piece of code that is called by a name that is associated with an object. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).
- All because of a class
Look the code below. A class called Door
which has a method(action) called open
. There is another portion of code with def
just below which defines a function, it is a function because it is not declared inside a class, this function calls the method we defined inside our class as you can see and finally the function is being called by itself.
class Door: def open(self): # <- method print 'hello' def knock_door: # <- function a_door = Door() Door.open(a_door) knock_door()