Python导入错误:继承类tenth_Frame无法导入基类Frame的问题
Hey there! Let's break down and fix this import mess you're dealing with—you're hitting a classic circular import issue, where your modules are trying to import each other before their classes are fully defined. Let's walk through the fixes step by step.
The Core Problem
Your current code creates a tangled web of cross-imports:
GameimportsFrame,Roll,tenth_FrameFrameimportsGameRollimportsFrameandGametenth_FrameimportsFrame
When Python tries to load these modules, it gets stuck in a loop—by the time tenth_Frame tries to import Frame, Frame might not have finished loading yet (because it's waiting on Game to load, which is waiting on tenth_Frame).
Step 1: Clean Up Unnecessary Imports
Most of your cross-imports are totally unnecessary. Let's strip them out:
Roll.py
This class only generates random pin counts—no need to depend on Game or Frame at all:
import random class Roll: # Example method to return knocked-down pins def get_pins(self): return random.randint(0, 10)
Module_Frame.py
You don't need to import Game here—Python doesn't require you to import a class just to accept it as a parameter. Just keep the import for Roll:
from Roll import Roll class Frame(): def __init__(self, game): self._score = 0 self._moves = Roll() self.game = game self.make_move() # Add your make_move and other methods here def make_move(self): # Your frame logic goes here pass
Step 2: Fix tenth_Frame.py Import
Now that Module_Frame no longer depends on Game, you can safely import Frame and inherit from it properly:
from Module_Frame import Frame class tenth_Frame(Frame): def __init__(self, game): super().__init__(game) # Use super() for cleaner parent class initialization self.__sum = 0 # Add your tenth frame-specific methods here
Step 3: Adjust Game.py Import Order
As the top-level module, Game should import its dependencies in a way that avoids triggering leftover loops. Update it to:
from Roll import Roll from Module_Frame import Frame from tenth_Frame import tenth_Frame class Game: def __init__(self): self.frames = [] # Initialize 9 regular frames + 1 tenth frame for _ in range(9): self.frames.append(Frame(self)) self.frames.append(tenth_Frame(self)) # Add your game logic (score calculation, etc.) here
Why This Works
By removing the unnecessary cross-imports, we break the circular dependency chain. Now:
Rollis independentFrameonly depends onRolltenth_Frameonly depends onFrameGameimports all other modules after they've been fully defined
This lets Python load each module in a clean, linear order without getting stuck.
内容的提问来源于stack exchange,提问作者Chris

