我和我的朋友正在用Python制作象棋AIs,但是我们在enum方面遇到了一个神秘的问题。我们对枚举中的片段类型进行如下编码:
你知道吗件.py地址:
from enum import Enum
class PieceType(Enum):
type_one = 1
...
def recognise_type(my_type):
print("Passed ", my_type)
if my_type is PieceType.type_one:
print("Type One")
else:
print("Type not recognised")
我们要求人工智能提供一块(例如提升一个棋子),并称之为“U类型”:
你知道吗艾比地址:
import Piece
def get_promotion():
return Piece.PieceType.type_one
你知道吗小虫.py地址:
import Piece
import ai
my_type = ai.get_promotion()
Piece.recognise_type(my_type)
到目前为止还不错;跑步小虫.py输出如下:
Passed PieceType.type_one
Type One
但事情是这样的。这个包裹的名字是“Chess”,但是如果在艾比我们将import Piece
改为from Chess import Piece
(例如,如果我们想艾比在另一个包中),然后出了问题。跑步小虫.py现在给出:
Passed PieceType.type_one
Type not recognised
这里发生了什么?为什么在import语句中包含包名会破坏枚举比较?你知道吗
就Python而言,您正在导入一个不同的模块;您有
Piece
和Chess.Piece
。Python将为这两个模块创建单独的模块对象,每个模块都有一个单独的enum类。这些类上的值永远不会被测试为相等。你知道吗如果您的所有模块都是
Chess
包的一部分,那么您应该而不是将该包中的文件视为顶级模块。这意味着您不应该将该目录添加到Python路径中(通过使用该目录中的脚本显式或隐式地)。你知道吗相关问题 更多 >
编程相关推荐