'float' 在 Python 中从 Enum 创建字典时对象不可调用

'float' object is not callable while creating dictionary from Enum in Python

我在 Python 3.4 中创建了一个枚举,其中包含一些数据和一个 returns 基于枚举的 ffactor 函数。我想从每个枚举中制作一个 ffactors 字典。所以我尝试了这个:

class RaceType(Enum):
    GS = 0 
    SC = 1 
    CL = 2 
    @property
    def ffactor(self):
        if self is RaceType.GS:
            return 660.0
        if self is RaceType.SC or self is RaceType.CL:
            return 500.0

zeroes = {this: this.ffactor() for this in RaceType}

然而,这引发了一个错误:

Traceback (most recent call last):
  File "parse.py", line 28, in <module>
    zeroes = {this: this.ffactor() for this in RaceType}
  File "parse.py", line 28, in <dictcomp>
    zeroes = {this: this.ffactor() for this in RaceType}
TypeError: 'float' object is not callable

我尝试手动写出我想要的内容,但仍然出现相同的错误:

zeroes = {RaceType.GS: RaceType.GS.ffactor(),
          RaceType.SC: RaceType.SC.ffactor(),
          RaceType.CL: RaceType.CL.ffactor()}

我该如何解决这个问题?

您将 ffactor 定义为 @property,这意味着它的行为类似于属性而不是方法。

In [4]: zeroes = {this: this.ffactor for this in RaceType}

In [5]: zeroes
Out[5]: {<RaceType.SC: 1>: 500.0,
         <RaceType.GS: 0>: 660.0,
         <RaceType.CL: 2>: 500.0}