Class attributes & properties

Classes & Objects, lesson 3 of 6

🏗️ Classes & Objects, lesson 3 of 6

Class attributes & properties

Share data across all instances and add smart, validated attributes.

11 min

1 exercise

1 quiz

0/2 solved

Getting Python ready… examples can run in a moment.

Attributes set on self belong to one object. Attributes written directly in the class body are class attributes, shared by every instance. They're handy for constants and for counters.

When you read obj.attr, Python looks on the object first, then on its class.

Example

Shared vs per-object data

Changing Pizza.base_price updates every pizza at once. Make a third pizza and check Pizza.made.

Example

The shared-list trap

Ben got Ann's grade! Delete grades = [] from the class body and add self.grades = [] inside __init__ to fix it.

Quiz

What does this print?

Properties: attributes with logic. Put @property above a method and you read it like an attribute, without parentheses. Use it for values computed from other attributes.

Add a setter to run code when the attribute is assigned, for example to validate it. A leading underscore (self._balance) marks the real storage as internal.

Example

A computed property

No parentheses, yet it's recomputed each time. Try t.fahrenheit = 50: a property without a setter is read-only.

Example

Validating with a setter

Even __init__ goes through the setter, so Account("Leo", -5) fails too. Try it.

Exercise

A validated Circle

Upgrade Circle:

  1. A read-only property diameter (2 × radius)
  2. A read-only property area (π × radius²)
  3. Make radius a property whose setter raises ValueError for negative values