Defining methods

Contents

Defining methods#

So far, we’ve defined fields, but the only method we’ve defined is the specially named __init__ constructor. Let’s do some more interesting work!

To define a method, you add def NAME(self, ARGS, ...) to the class definition block, like so:

Ah: a simple counter! You can define as many methods as you like. Here, we define a version with a reset method that sets the value back to 0:

The order in which you define methods doesn’t matter at all—they all just go in the class definition block.

Method arguments#

Methods take arguments, just like functions. Here’s a counter that lets you increment by some amount: