Python @property decorator

1) Simple @property

Create a class Person with a private attribute _name. Use @property so p.name returns the value.


2) Property With Setter

Extend the above so you can assign to p.name = "Alice" using a @name.setter.


3) Read-Only Property

Create a class Circle with private _radius. Add a read-only property radius (no setter).


4) Computed Property

In Circle, add a property area that returns π × r² (use math.pi).


5) Property With Validation

Create a class Student with private _age. In the setter for .age, ensure age ≥ 0; if not, print an error.


6) Property That Formats

Create a class Person where .fullname returns "First Last". Store first and last privately.


7) Auto-Compute Property

Add a class Rectangle with _width and _height. Add property perimeter that returns 2 × (w + h).


8) Property Without Setter

Create a class Temperature with private _celsius. Only allow reading .celsius — no setter.


9) Write-Only Property

Create a property password with only a setter; store hashed or just print “Set!”


10) Lazy Computed Property

Create a property in a class that prints “Computing…” the first time it’s read.


11) Property That Counts Access

Create a property that increments a counter each time it is accessed.


12) Property Using Different Internal Name

Store _x but expose .value as property (both get/set).


13) Protected Setter

Make .age set only if value is an integer; otherwise ignore.


14) Property Returning List Length

Given class with a private list _items, add property .count that returns its length.


15) Property That Uppercases

Property name returns uppercase form of the internal string.


16) Property With Print

Every time the property is accessed, print “Accessing…”.


17) Property That Prevents Negative

Given class with _balance, setter for .balance prevents negative values.


18) Property That Logs Change

Setter for .score prints old and new value whenever .score = … is assigned.


19) Chained Properties

Create Point class with .x and .y properties backed by _x, _y.


20) Property to Upper/Lower

Given class with internal _text, create two properties:

  • .upper returns uppercase

  • .lower returns lowercase


🧠 Concepts Covered

Feature
Practice

Defining properties

@property def name

Setters

@name.setter

Read-only properties

no setter

Computed values

value derived from internals

Validation inside setter

control assignment

Side effects

printing/logging when accessed


📌 Minimal Starter Template


📝 Quick Tips

  • Use private attribute naming (e.g., _x) for backing store.

  • @property makes a method look like a field.

  • You can define getters, setters, and deleters with decorators.


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated