# @property

[https://www.programiz.com/python-programming/property](https://www.programiz.com/python-programming/property)

@property 把方法變成 "屬性"

## @property

```python
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

```python
property(fget=None, fset=None, fdel=None, doc=None)
```

### usage

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

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

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value
```
