Python
  • index
  • Basic - 1
  • Basic - 2
  • SQLAlchemy
  • Decorator
  • @property
  • __dict__
  • pathlib
  • class
  • flask
  • Jupyter Notebook
  • PyQt
  • UD - FLASK - PY Basic
  • UD - FLASK - REST
  • UD - FLASK - vanilla SQL
  • UD - FLASK - SQLAlchemy
  • UD - FLASK - JWT
  • UD - FLASK - Serialization
Powered by GitBook
On this page
  • @property
  • property definition
  • usage

Was this helpful?

@property

PreviousDecoratorNext__dict__

Last updated 5 years ago

Was this helpful?

@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

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

usage

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
https://www.programiz.com/python-programming/property