Paul's Python CoursePPC

Methods

Not met yet

A method is a function defined inside a class. Call it on an object, red.hire("Yahya"), and Python passes that object in as the first parameter, self. Methods that change the object set attributes on self; methods that answer a question return a value. Bike.hire(red, "Yahya") is the same call written the long way.

Try it

main.py
class Counter:
    def __init__(self):
        self.count = 0

    def tick(self):
        self.count += 1
        return self.count

c = Counter()
c.tick()
print(c.tick())

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks calling a method on the class, like Bike.hire("Ann"), changes the objects made from it.
  • Thinks calling a method on the class makes a new object to call it on.

Where it comes up