TypeError:“NoneType”对象在创建obj实例时不可调用

2024-10-03 15:34:42 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,下一件事困扰着我:

我想用下一堂课:

class GameStatus(object):
"""Enum of possible Game statuses."""
__init__ = None
NotStarted, InProgress, Win, Lose = range(4)
def getStatus(number):
    return{
        0: "NotStarted",
        1: "InProgress",
        2: "Win",
        3: "Lose",
        }

在另一个类中(都在同一个py文件中)。 在这个方法的另一个类中,我做下一件事:

^{pr2}$

当我尝试运行游戏时,我收到下一条错误消息:

File "C:\Users\Dron6\Desktop\Study\Python\ex6\wp-proj06.py", line 423, in __init__
gs = GameStatus()
TypeError: 'NoneType' object is not callable

我做错什么了?在


Tags: ofpygameobjectinitenumwinclass
2条回答

您正在将GameStatus初始值设定项设置为None

class GameStatus(object):
    __init__ = None

别那样做。Python期望这是一个方法。如果您不想使用__init__方法,根本就不要指定它。最多,使其成为空函数:

^{pr2}$

如果您想创建一个类似枚举的对象,请看一下How can I represent an 'Enum' in Python?

对于Python 2.7,可以使用:

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums['reverse_mapping'] = reverse
    return type('Enum', (), enums)

GameStatus = enum('NotStarted', 'InProgress', 'Win', 'Lose')

print GameStatus.NotStarted          # 0
print GameStatus.reverse_mapping[0]  # NotStarted

好吧,经过小范围的研究,我发现了问题所在。 我得到的密码是:

class GameStatus(object):
    """Enum of possible Game statuses."""
    __init__ = None
    NotStarted, InProgress, Win, Lose = range(4)

我需要把名字转换成他们的价值。 所以我建立了:

^{pr2}$

我不能使用它,因为我不能创建一个对象,而且这个方法不是静态的。 解决方案:在方法之前添加@staticmethod。在

另外,我在返回开关上有一个小错误,正确的版本是:

@staticmethod
def getStatus(number):
return{
    0: "NotStarted",
    1: "InProgress",
    2: "Win",
    3: "Lose",
    }[number]

感谢所有试图帮忙的人。在

相关问题 更多 >