Skip to main content
 首页 » 编程设计

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

2025年05月04日54zhengyun_ustc

我在 Python 3.4 中创建了一个枚举,其中包含一些数据和一个基于枚举返回 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}