我建议您重构代码,正如其他人建议的那样。
我可以向您展示我最近遇到的一个循环错误:
之前:
from spell import Heal, Lightning
class Person:
def __init__(self):
self.life = 100
class Jedi(Person):
def heal(self, other: Person):
Heal(self, other)
class Sith(Person):
def lightning(self, other: Person):
Lightning(self, other)
from person import Person, Jedi, Sith
class Spell:
def __init__(self, caster: Person, target: Person):
self.caster: Person = caster
self.target: Person = target
class Heal(Spell):
def __init__(self, caster: Jedi, target: Person):
super().__init__(caster, target)
target.life += 10
class Lightning(Spell):
def __init__(self, caster: Sith, target: Person):
super().__init__(caster, target)
target.life -= 10
from person import Jedi, Sith
步骤如下:
from person import Jedi, Sith
from spell import Heal, Lightning
from person import Person, Jedi, Sith
控制台:
ImportError: cannot import name 'Person' from partially initialized module
'person' (most likely due to a circular import)
一个脚本/模块只能被一个脚本导入。
之后:
class Person:
def __init__(self):
self.life = 100
from person import Person
class Spell:
def __init__(self, caster: Person, target: Person):
self.caster: Person = caster
self.target: Person = target
from person import Person
from spell import Spell
class Jedi(Person):
def heal(self, other: Person):
Heal(self, other)
class Heal(Spell):
def __init__(self, caster: Jedi, target: Person):
super().__init__(caster, target)
target.life += 10
from person import Person
from spell import Spell
class Sith(Person):
def lightning(self, other: Person):
Lightning(self, other)
class Lightning(Spell):
def __init__(self, caster: Sith, target: Person):
super().__init__(caster, target)
target.life -= 10
from jedi import Jedi
from sith import Sith
jedi = Jedi()
print(jedi.life)
Sith().lightning(jedi)
print(jedi.life)
执行代码行的顺序:
from jedi import Jedi
from person import Person
from spell import Spell
from person import Person
控制台:
100
90
文件组成是关键,希望能对你有所帮助 :D
self
的类型,因为它总是当前类的子类(任何类型检查系统都应该能够自行解决这个问题)。func2
是否尝试调用在MyMixin
中未定义的func1
?也许应该将其定义为抽象方法 (abstractmethod
)? - Blckknghtclass Main(MyMixin, SomeBaseClass)
,以便来自更具体类的方法可以覆盖来自基类的方法。 - Anentropic