我和我的 friend 正在用 Python 制作国际象棋 AI,但我们遇到了一个关于枚举的神秘问题。我们在枚举中对片段类型进行编码,如下所示:
件.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")
我们向 AI 请求一个棋子(例如提升一个棋子)并调用 recognise_type:
.py:
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)
到现在为止还挺好;运行 bug.py 输出以下内容:
Passed PieceType.type_one
Type One
但事情是这样的。这个包的名字是'Chess',但是如果在ai.py 中我们将
import Piece
更改为from Chess import Piece
(例如,如果我们想将ai.py 放在不同的包中),那么就会出现问题。运行 bug.py 现在给出:Passed PieceType.type_one
Type not recognised
这里发生了什么事?为什么在 import 语句中包含包名会破坏枚举比较?
最佳答案
就 Python 而言,您正在导入一个不同的模块;你有 Piece
,你有 Chess.Piece
。 Python 将为这两个模块创建单独的模块对象,每个模块都有一个单独的枚举类。这些类的值永远不会被测试为相等。
如果您的所有模块都是 Chess
包的一部分,那么您不应将该包中的文件视为顶级模块。这意味着您不应将该目录添加到您的 Python 路径中(通过使用该目录中的脚本显式或隐式地添加)。
关于python - 在 Python 中使用包名破坏枚举比较导入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30733271/