Ask a dog to sit and ask a cat to sit, and you get different results, because the action depends on who is doing it. Methods follow similar logic. They are written inside a class, and when you call one, it runs against the particular object you called it on, reading and updating that object's own data.
You call a method with dot notation: the object, a dot, then the method name, as in playlist.add(song). Chances are you have used methods already without noticing. In Python, "hi".upper() calls the upper method of a string.
Example
class Counter:
def __init__(self):
self.count = 0
def increment(self, step=1):
self.count += step
return self.count
clicks = Counter()
clicks.increment()
print(clicks.increment(5)) # 6
Inside the class, self refers to whichever object the method was called on. Python supplies it automatically, so clicks.increment(5) behaves like Counter.increment(clicks, 5). Java and JavaScript use the keyword this for the same idea, and PHP uses $this.
Method vs function
Both are named, reusable blocks of code, and they look almost identical on the page. The difference is ownership. A function such as Python's built-in len(items) is called by its name alone and only sees the arguments passed in. A method is defined inside a class and is reached through an instance, which gives it access to that instance's attributes.
One variation is worth knowing early. Static methods belong to the class as a whole rather than to one object, so you can call them without creating an instance first, for example Math.max(3, 9) in Java.
Next steps
- Python course
- Run the
Counterexample in the Python editor - Programming fundamentals
Last updated