Python解决循环导入而不合并文件

伴侣维塔

我有一段代码定义了游戏中可能的物品类型和结界类型。一些附魔类型彼此不兼容,或者与某些物品类型不兼容。我希望每种物品类型都具有与结界不兼容的信息,并且希望每个附魔都包含与之兼容的物品的信息,而不必不断地查找其中的一个。

items.py

from enum import Enum, auto

class ItemType(Enum):
  PLATE = auto()
  HELMET = auto()
  BOOTS = auto()
  SWORD = auto()
  BOW = auto()
# Get compatible enchantment types
from enchantments import EnchantmentType
for it in ItemType:
  it.compatible_enchantments = set(filter(lambda ench: it in ench.compatible_items, EnchantmentType))


class Item:
  def __init__(self, item_type, enchantments=None):
    self.type = item_type
    self.enchantments = []
    if enchantments:
      for ench in enchantments:
        self.add_enchantment(ench)

  def add_enchantment(self, enchantment, i=None):
    if enchantment.type not in self.compatible_enchantments:
      raise ValueError(f"Enchantment {enchantment.type} is incompatible with {self.type}.")
    if i is None:
      self.enchantments.append(enchantment)
    else:
      self.enchantments.insert(enchantment, i)    from enum import Enum
from items import ItemType as IT

enchantments.py

from enum import Enum, auto

class EnchantmentType(Enum):
  ENHANCED_ARMOUR = IT.HELMET, IT.PLATE, IT.BOOTS, IT.RING
  ENHANCED_DAMAGE = IT.SWORD, IT.BOW, IT.RING
  YELLOW_COLOUR = ()

  def __init__(self, *compatible_item_types):
    self.compatible_items = set(IT) if not compatible_item_types else compatible_item_types
    self.incompatible_enchantments = set()
# Fill in the incompatible enchantments
for mutualy_exclusive_group in (
    {EnchantmentType.ENHANCED_ARMOUR, EnchantmentType.ENHANCED_DAMAGE}
):
  for ench in mutualy_exclusive_group:
    ench.incompatible_enchantments += mutualy_exclusive_group - {ench}


class Enchantment:
  def __init__(self, enchantment_type, level=None):
    self.type = enchantment_type
    self.level = level

main.py

from enchantments import EnchantmentType as ET

print(ET.ENHANCED_ARMOUR.compatible_items)
print(ET.ENHANCED_DAMAGE.compatible_items)
print(ET.YELLOW_COLOUR.compatible_items)

运行此代码使我ImportError引述了循环导入。

按照此答案,我尝试将from x import y语句更改为import x但仍然遇到相同的错误。

我已经暂时通过删除解决这个问题from enchantments import EnchantmentType,从items.py与移动线

from enchantments import EnchantmentType
for it in ItemType:
  it.compatible_enchantments = set(filter(lambda ench: it in ench.compatible_items, EnchantmentType))

进入enchantments.py但是,这要求任何希望获得有关附魔的正确信息的模块都必须手动导入enchantments.py-items.py导入将导致所有模块compatible_enchantments为空。

有没有一种方法可以在不合并两个文件的情况下使循环导入工作?

安德鲁·麦克莱门特

而不是compatible_enchantments在每个ItemType上进行设置,为什么不在某个地方(可能在enchantments.py中)有一个字典将EnchantmentType映射到可以应用的有效ItemType上呢?

对我来说,似乎ItemType不需要了解结界,但是结界需要知道它们是否可以应用于特定的ItemType。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章