Methods

Classes & Objects, lesson 2 of 6

🏗️ Classes & Objects, lesson 2 of 6

Methods

Give objects behavior with functions that live inside the class.

10 min

1 exercise

1 quiz

0/2 solved

Getting Python ready… examples can run in a moment.

A method is a function defined inside a class. Its first parameter is always self, so it can read and change the object's attributes.

You call it with a dot: c.click(). Python passes c in as self automatically.

Example

Methods change an object's state

Give click a parameter step=1 and use self.count += step, then call c.click(5).

Example

Methods that return values

Methods can call other methods through self. After changing width, area() gives a new answer because it's computed on every call.

Quiz

What does this print?

Objects can interact. A method can take another object as an argument and call its methods or change its attributes.

Example

A tiny battle

Change the troll's power to 12. Who wins now?

Exercise

A shopping cart

Complete the three methods of Cart:

  • add(name, price) appends a (name, price) tuple to self.items
  • total() returns the sum of all prices
  • most_expensive() returns the name of the priciest item, or None for an empty cart