最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【基本解决】python中的property

Python crifan 2669浏览 0评论

折腾:

【已解决】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_gravity
9.802652743337129

想要搞清楚:

Python中的property的用法和含义

以便于后续去实现enum类中的方法,函数

搜:

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

【总结】

目前看起来的是:

原先对于一个类中的属性,有getter,setter,deleter三个方法,对应实现的写法是:

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.”)

而如果用property的话,默认就是getter:

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

如果需要,可以再加入setter,deleter:

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

转载请注明:在路上 » 【基本解决】python中的property

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
81 queries in 0.186 seconds, using 22.12MB memory