Python中已有一个枚举类型:
import enum class TipType(enum.Enum): NoTip = “NoTip” TenPercent = “TenPercent” FifthPercent = “FifthPercent” TwentyPercent = “TwentyPercent” |
现象想要:
定义一个内部的函数,可以将当前的枚举类型,转换得到一个小费的百分比
python enum class function
8.13. enum — Support for enumerations — Python 3.6.0b4 documentation
看到有:
… @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) |
去试试:
python enum property
python enum method
-》
换句话说,如果需要:
一个类中的属性,才需要用property
-》我此处,就只是返回一个映射关系的数据而已,所以:
估计用不用property都是可以的
但是由于我此处没有对应的,类的函数同名的属性:
class TipType(enum.Enum): NoTip = “NoTip” TenPercent = “TenPercent” FifthPercent = “FifthPercent” TwentyPercent = “TwentyPercent” @property def getTipPercent(self): tipPercent = 0.0 if self == TipType.NoTip: tipPercent = 0.0 elif self == TipType.TenPercent: tipPercent = 0.10 elif self == TipType.FifthPercent: tipPercent = 0.15 elif self == TipType.TwentyPercent: tipPercent = 0.20 gLog.debug(“self=%s -> tipPercent=%s”, self, tipPercent) return tipPercent |
即:
没有对应的getTipPercent这个属性
,所以则不应该用property才对。
-》
所以
【总结】
Enum中,改为普通的class中的函数:
class TipType(enum.Enum): NoTip = “NoTip” TenPercent = “TenPercent” FifthPercent = “FifthPercent” TwentyPercent = “TwentyPercent” # @property def getTipPercent(self): tipPercent = 0.0 if self == TipType.NoTip: tipPercent = 0.0 elif self == TipType.TenPercent: tipPercent = 0.10 elif self == TipType.FifthPercent: tipPercent = 0.15 elif self == TipType.TwentyPercent: tipPercent = 0.20 gLog.debug(“self=%s -> tipPercent=%s”, self, tipPercent) return tipPercent |
就可以了。
调用方法就是普通的函数调用:
tipPercent = initiatorTipType.getTipPercent() |
即可输出结果。
tipPercent=0.1 |
转载请注明:在路上 » 【已解决】Python中给枚举添加内置函数或属性