Python Method
Python Method is called by its name, but it is associated to an object (dependent).
A method definition always includes ‘self’ as its first parameter.
A method is implicitly passed the object on which it is invoked.
It may or may not return any data.
A method can operate on the data (instance variables) that is contained by the corresponding class
Functions
Function is block of code that is also called by its name. (independent)
The function can have different parameters or may not have any at all. If any data (parameters) are passed,
they are
passed explicitly.
It may or may not return any data.
Function does not deal with Class and its instance concept.
A method is a function which is applicable to a certain class, while a function can be used in any valid
class. Like
the sort method for the list class sorts the list. Methods of mutable types mostly change the item, so
list.sort would
set the value of list to the sorted value of list and return None. But methods of immutable types like
strings
will
return a new instance of the thing as seen below.
question = "How is this?"
question.replace("How", "What") # Returns "What is this", but does not change question.
print(question) # Prints "How is this?"
print(question.replace("How", "What")) # Prints "What is this"
Built in functions like sorted do not change the item, they return a new version, or instance, of it.
list1 = [4,3,6,2]
sorted(list1) # Returns [2,3,4,6], but does not modify list.
print(list1) # Prints [4,3,6,2]
list1.sort() # Returns None, but changes list.
print(list1) # Prints [2,3,4,6]
When you use a method, you put a period after the variable to show that it can only be used for that specific
class. Why
some functions require arguments while some methods don't - like sorted(list) requires list, but list.sort()
doesn't
require arguments, is that when you use a method on a class, Python by default passes in a parameter called
self, which
is the actual variable, list in this case. If you have worked with JavaScript, self is something like the this
keyword
in JS.
So when you enter list.sort(), Python is actually running the function sort inside the list class passing it a
parameter
of self.
More Python tutorial.
Python Tutorials pdf