Codiqo

Learn Python · lesson 43 of 60 · about 9 minutes

Methods and Attributes

Look after Sam's basil plant: give objects behaviour with methods that read and change their own attributes.

What you'll learn

  • Write methods that use self
  • Change state through methods
  • Add a __str__ for nice printing

The basil plant

Sam is growing basil on the windowsill. A Plant starts with 3 units of water out of 5. Each day day_passes() uses 1 (never below 0), and on days Sam waters it, give_water() adds 2 (never above 5). Sam types one letter per day, like nnyn, and the assistant lets each day pass and waters on the y days. A __str__ method decides what printing the plant shows: Basil: water 1/5, or Basil: dry, water it now! at 0.

Data plus behaviour

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: pet.feed(). Python passes the object in as self for you.

A pet with methods

class Pet:
    def __init__(self, name):
        self.name = name
        self.hunger = 5

    def feed(self, amount):
        self.hunger = max(0, self.hunger - amount)

    def status(self):
        return f"{self.name}: hunger {self.hunger}"

p = Pet("Phoebe")
p.feed(2)
print(p.status())
p.feed(10)
print(p.status())

Output

Phoebe: hunger 3
Phoebe: hunger 0

Printing objects nicely

Printing an object normally shows something like <__main__.Pet object at 0x...>. A __str__ method tells Python what text to show instead.

__str__

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"({self.x}, {self.y})"

print(Point(2, 5))

Output

(2, 5)

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.