Python ProgrammingPython Programming

How does the @property decorator work in Python?

class Currency:
    def __init__(self, dollars, cents):
        self.total_cents = dollars * 100 + cents

    @property
    def dollars(self):
        return self.total_cents // 100

    @dollars.setter
    def dollars(self, new_dollars):
        self.total_cents = 100 * new_dollars + self.cents

    @property
    def cents(self):
        return self.total_cents % 100

    @cents.setter
    def cents(self, new_cents):
        self.total_cents = 100 * self.dollars + new_cents


currency = Currency(10, 20)
print(currency.dollars, currency.cents, currency.total_cents)

currency.dollars += 5
print(currency.dollars, currency.cents, currency.total_cents)

currency.cents += 15
print(currency.dollars, currency.cents, currency.total_cents)
Output
10 20 1020
15 20 1520
15 35 1535