Validate state with properties and class methods
Keep validation in a setter and use a class method as an alternate constructor.
Jump to the automation labA @property lets callers read through attribute syntax while running a getter method. A setter can enforce the same rule on initialization and later assignment. Store the validated value under another name such as _celsius to avoid calling the setter recursively.
A @classmethod receives the class as cls, so it can construct an object using another representation. A @staticmethod receives neither the class nor the instance automatically. It fits a helper closely related to the class that does not need its state.
Values assigned on the class are shared by default. Use class attributes for shared constants and use instance attributes for each object’s own state.
Convert the input to Celsius before constructing an object.
Worked examples
Use a static method for a pure conversion
The conversion needs only its argument. The static method has no implicit self or cls parameter.
class Units:
@staticmethod
def meters_to_centimeters(meters):
return meters * 100
print(Units.meters_to_centimeters(1.75)) # 175.0Run the example and practice
Make from_fahrenheit convert degrees to Celsius using (fahrenheit - 32) * 5 / 9. Keep the existing setter.
Target output
20.0 CShow a hint
Compute the converted number first and pass it to cls(...).
Ready
Run your code to see the output here.
Check output also tests your code with additional cases.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
class Temperature:
ABSOLUTE_ZERO = -273.15
def __init__(self, celsius):
self.celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < self.ABSOLUTE_ZERO:
raise ValueError("below absolute zero")
self._celsius = value
@classmethod
def from_fahrenheit(cls, fahrenheit):
return cls((fahrenheit - 32) * 5 / 9)
reading = Temperature.from_fahrenheit(68)
print(f"{reading.celsius:.1f} C")Automation lab
Measure images before making previews
Construct a size from a Pillow image and expose its pixel count as a computed property.
Ready
Run the example to see the output here.
Double one dimension and predict what happens to the pixel count.
Further reading in Automate the Boring Stuff with Python by Al Sweigart