🏗️ 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.
Shared vs per-object data
Changing Pizza.base_price updates every pizza at
once. Make a third pizza and check Pizza.made.
The shared-list trap
Ben got Ann's grade! Delete grades = [] from the
class body and add self.grades = [] inside
__init__ to fix it.
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.
A computed property
No parentheses, yet it's recomputed each time. Try
t.fahrenheit = 50: a property without a setter is
read-only.
Validating with a setter
Even __init__ goes through the setter, so
Account("Leo", -5) fails too. Try it.
A validated Circle
Upgrade Circle:
- A read-only property
diameter(2 × radius) - A read-only property
area(π × radius²) - Make
radiusa property whose setter raisesValueErrorfor negative values