@property

https://www.programiz.com/python-programming/property

@property 把方法變成 "屬性"

@property

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


>>> man = Celsius()
>>> man.temperature = 37 # setter
>>> man.temperature # getter
37
>>> man.to_fahrenheit()
98.60000000000001
>>> man.__dict__
{'temperature': 37}

__dict__keep object's attribute, but it will be verbose when we want to add additional getter & setter.

property definition

usage

Last updated

Was this helpful?