我陷入了一个错误,即使我确信我导入正确,但您仍收到名称错误。因此,我尝试从一个文件创建一个引用另一个文件的类实例。主文件中的导入如下所示
from movement import *
from maps import *
import pygame
import sys
pygame.init()
# Player class is in the movement file
player1 = Player(300, 300, 50, 50, 50)
这是运动文件
from maps import *
from main import *
import pygame
pygame.init()
objectAmount = 0
class Player:
def __init__(self, pos_x, pos_y, width, height, speed):
self.pos_x = pos_x
self.pos_y = pos_y
self.speed = speed
self.width = width
self.height = height
self.player_image = pygame.image.load("Munir.png")
self.image_rect = self.player_image.get_rect()
我尝试使用导入运动
和从运动导入播放器
没有成功解决问题。我猜问题可能在于我导入了多个文件?你毫 headless 绪。以下是错误信息
NameError: name 'Player' is not defined
最佳答案
问题是您在 Action 文件中再次导入 main。
这是因为导入一个文件基本上就是运行它,所以当你运行 main.py 时,你导入了 moving.py,你要做的第一件事就是再次导入 main。 python 中的一些功能允许循环导入,这就是为什么它不会再次导入时刻,从而导致无限循环。所以python不会再次导入 Action ,而是厌倦创建一个Player实例,但是Player还没有被定义。
您有两种解决方案,要么不从 Action 文件中导入 main,要么将 player1 = Player(300, 300, 50, 50, 50)
移动到它自己的类+方法中。例如带有 run() 方法的 MainGame 类。或者将它们移动到一个 block 中,例如:
if __name__ == "__main__":
player1 = Player(300, 300, 50, 50, 50)
#... main loop of your game.
该条件是一个简单的条件,仅当您运行 python 文件而不是导入它时才成立。
这样你就可以在 main.py 中定义一些可以在 Action 中使用的东西。但是,最好不要使用循环导入。
仅供引用,查看堆栈跟踪很有用,在这里您可以看到它如何从 main 进入运动,然后返回 main 并导致错误,而不是导入运动,然后继续在 main 内部运行。
Traceback (most recent call last):
File "main.py", line 1, in <module>
from movement import *
File "/home/user/temp/so/movement.py", line 2, in <module>
from main import *
File "/home/user/temp/so/main.py", line 9, in <module>
player1 = Player(300, 300, 50, 50, 50)
NameError: name 'Player' is not defined
希望有帮助!
关于python - 名称 "ClassName"未定义,即使我确信我导入正确(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53895080/