Skip to the content

Properties

Python · Unit 14: Modern classes

Some data isn't stored, it's worked out: the area of a rectangle comes from its width and its height.

With @property above a method, that method is used as if it were an attribute: r.area, with no parentheses.

class Rect:
    def __init__(self, w, h):
        self.w = w
        self.h = h

    @property
    def area(self):
        return self.w * self.h

r = Rect(3, 4)
print(r.area)

Prints

12

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete it so the diameter reads like an attribute.

  2. 2. Find the bug

    The rectangle is 3 by 4, so it should print 12. Which line has the error?

  3. 3. Predict the output

    The order was 3 pieces at 20 and then it changed to 5. What does it print?

  4. 4. Multiple choice

    When is a @property better than a normal attribute?

  5. 5. Complete the code

    The flask holds 500 ml. Complete it so it prints 500.

  6. 6. Predict the output

    The box holds 10 pieces. What does it print?

  7. 7. Find the bug

    It should print 7, the level the tank was given. Which line has the error?

  8. 8. Predict the output

    What does this code print?

  9. 9. Put the lines in order

    Put the lines in order so it prints the area of the square, 25.

  10. 10. Find the case that fails

    fill(cap, litres) puts those litres into a tank that holds cap and returns how many ended up inside: never more than the cap and never less than 0. Which call breaks it?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →