🏗️ 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.
Methods change an object's state
Give click a parameter step=1 and use
self.count += step, then call c.click(5).
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.
What does this print?
Objects can interact. A method can take another object as an argument and call its methods or change its attributes.
A tiny battle
Change the troll's power to 12. Who wins now?
A shopping cart
Complete the three methods of Cart:
add(name, price)appends a(name, price)tuple toself.itemstotal()returns the sum of all pricesmost_expensive()returns the name of the priciest item, orNonefor an empty cart