Ever felt limited by plain variables in your Python classes? Fear not, the @property
decorator swoops in like a superhero to add some superpowers * to your code!
With @property
, accessing a variable becomes an action, not just a read. Let's see how it elevates our humble Fraction
class:
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
@property
def value(self):
"""Calculates and returns the actual fraction value."""
if self.denominator == 0:
raise ZeroDivisionError("Oops! Denominator can't be zero.") # Handle division by zero
return self.numerator / self.denominator
@value.setter # Setter for the "value" property
def value(self,
new_value_tuple
):
"""Sets the numerator and denominator based on the provided value."""
numerator, denominator = new_value_tuple
self.numerator = numerator
self.denominator = denominator
Usage:
frac1=Fraction(1,2)
print( frac1.value ) #no need to use empty-braces "frac1.value()"
#call the "value" method decorated with @value.getter;
frac1.value = ( 3,4 ) #this is not name binding
#this calls the "value" method decorated with @value.setter and modifies the frac1 object
interactive example:
https://colab.research.google.com/drive/1eLdmgflqqG2UlUgbOyLzHM_8266T-NMr
Comments
Post a Comment