【基本解决】python中的property

Python 1957浏览

【已解决】Python中给枚举添加内置函数或属性

8.13. enum — Support for enumerations — Python 3.5.2 documentation

 >>> class Planet(Enum):…     MERCURY = (3.303e+23, 2.4397e6)…     VENUS   = (4.869e+24, 6.0518e6)…     EARTH   = (5.976e+24, 6.37814e6)…     MARS    = (6.421e+23, 3.3972e6)…     JUPITER = (1.9e+27,   7.1492e7)…     SATURN  = (5.688e+26, 6.0268e7)…     URANUS  = (8.686e+25, 2.5559e7)…     NEPTUNE = (1.024e+26, 2.4746e7)…     def __init__(self, mass, radius):…         self.mass = mass       # in kilograms…         self.radius = radius   # in meters…     @property…     def surface_gravity(self):…         # universal gravitational constant  (m3 kg-1 s-2)…         G = 6.67300E-11…         return G * self.mass / (self.radius * self.radius)…>>> Planet.EARTH.value(5.976e+24, 6378140.0)>>> Planet.EARTH.surface_gravity9.802652743337129

Python中的property的用法和含义

python property

Python @property: How to Use it and Why? – Programiz

python – How does the @property decorator work? – Stack Overflow

properties – Python @property versus getters and setters – Stack Overflow

Python3 Tutorial: Properties vs. getters and setters

2. Built-in Functions — Python 2.7.12 documentation

【总结】

 class C(object):    def __init__(self):        self._x = None    def getx(self):        return self._x    def setx(self, value):        self._x = value    def delx(self):        del self._x    x = property(getx, setx, delx, “I’m the ‘x’ property.”)

 class Parrot(object):    def __init__(self):        self._voltage = 100000    @property    def voltage(self):        “””Get the current voltage.”””        return self._voltage

 class C(object):    def __init__(self):        self._x = None    @property    def x(self):        “””I’m the ‘x’ property.”””        return self._x    @x.setter    def x(self, value):        self._x = value    @x.deleter    def x(self):        del self._x

87 queries in 0.111 seconds, using 20.65MB memory