Practice: Properties
Q1. Read-only area
Create class Square with attribute side and a property area (side*side). Print the area of Square(6).
Goal: Create a read-only property.
Q2. Full name
Create class Person with first and last attributes and a property full_name that joins them with a space. Print the full name for Asha Rao.
Goal: Create a computed property.
Q3. Age setter
Create class Student with a property age. The setter must raise ValueError for negative values. Set age to 15, print it, then try -4 and print 'invalid' when ValueError occurs.
Goal: Add validation with a setter.
Q4. Celsius to Fahrenheit
Create class Temp with attribute celsius and a property fahrenheit. Print the Fahrenheit value for 37 Celsius as a number rounded to 1 decimal place.
Goal: Use a property for conversion.
Q5. Price with minimum
Create class Item whose price property setter stores max(value, 0), so negative prices become 0. Create Item(50), then set price to -20 and print the price.
Goal: Modify values inside a setter.
Q6. Deleter reset
Create class Counter with a property count (starting at 5) and a deleter that sets the hidden value to 0. Delete the property and print count.
Goal: Use a deleter.
Q7. Rectangle output
What does this print?
class R:
def __init__(self, w, h):
self.w = w
self.h = h
@property
def area(self):
return self.w * self.h
r = R(3, 4)
r.w = 5
print(r.area)Goal: Predict a computed property.
Q8. Setter chain output
Predict the output.
class A:
def __init__(self):
self.x = 1
@property
def x(self):
return self._x
@x.setter
def x(self, v):
self._x = v * 2
a = A()
print(a.x)
a.x = 5
print(a.x)Goal: Trace a setter.
Q9. Read-only error
What does this print?
class P:
@property
def name(self):
return "fixed"
p = P()
try:
p.name = "new"
except AttributeError:
print("blocked")
print(p.name)Goal: Know read-only behaviour.
Q10. Property with print
What is printed, and in what order?
class T:
@property
def v(self):
print("reading")
return 10
t = T()
x = t.v
print(x + 1)Goal: See that a getter runs on every read.
Q11. Validated init
Predict the output.
class Box:
def __init__(self, size):
self.size = size
@property
def size(self):
return self._size
@size.setter
def size(self, v):
if v <= 0:
raise ValueError("bad")
self._size = v
try:
Box(0)
except ValueError as e:
print("error", e)Goal: Understand validation at creation.
Q12. Debug the recursion
This setter crashes with RecursionError. Fix it.
class C:
@property
def n(self):
return self.n
@n.setter
def n(self, v):
self.n = v
c = C()
c.n = 3
print(c.n)Goal: Avoid recursion in properties.
Q13. Debug the brackets
The code raises TypeError. Fix it.
class Dog:
def __init__(self):
self.name = "Rex"
@property
def shout(self):
return self.name.upper()
d = Dog()
print(d.shout())Goal: Read a property without brackets.
Q14. Debug missing setter
Assigning to the property raises AttributeError. Fix the class so the value can be changed.
class Acct:
def __init__(self):
self._bal = 0
@property
def bal(self):
return self._bal
a = Acct()
a.bal = 100
print(a.bal)Goal: Add a missing setter.
Q15. Why properties
Explain in two sentences why Python programmers prefer properties to get_x and set_x methods.
Goal: Explain the value of properties.
Q16. Where is the data
In a property named price, where is the value actually stored, and why not under the same name?
Goal: Understand storage behind properties.
Q17. Bank balance design
Write a class Wallet with a read-only property balance and methods add(n) and spend(n). spend must not allow the balance to go below zero (ignore the spend instead). Add 100, spend 30, spend 500, then print the balance.
Goal: Combine read-only properties and methods.
Q18. Grade label
Write class Marks with a settable score (0 to 100, otherwise ValueError) and a read-only property grade: 'A' for 90 or more, 'B' for 75 or more, otherwise 'C'. Print the grade for scores 95, 80 and 40 on separate lines.
Goal: Combine setter validation with a computed property.