我正试图学习如何改变我的程序,使他们使用多个python脚本的代码。我有两个脚本(这些都是大文件,所以把它们缩减到只需要的部分)
main.py
import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an instance of hero
player.py
import pygame
import main
class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()
运行此命令会出现以下错误:
AttributeError: 'module' object has no attribute 'hero'
我不太明白为什么它试图获得一个属性,而不是创建一个实例。我试着看其他的例子,他们是如何解决问题的,但当我试图把它应用到上面的代码,它不能解决我的问题。
-
要从其他模块导入
hero
,您应该写player.hero
,或者简单地写from player import hero
。 -
在
main
中导入player
,在player
中导入main
,会导致"循环引用"。
下面是修改后的代码:
main.py
import pygame
from player import hero # Imports the player.py script
p1 = hero("woody.png",[2,2]) # Creates an instance of hero
player.py
import pygame
class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()#.....etc
就像雅典娜上面说的,不要把main
导入player
,不要把player
导入main
。这会导致导入循环。只需将player
导入main
其次,如果您想使用player
模块中的hero
类,则必须说player.hero()
。或者如果你只想说hero()
,你可以说from player import*
。这告诉python将player
中的所有文件导入到命名空间main
中。
要小心使用,因为播放器文件中的函数或类可能与已经存在的同名函数或类冲突。
作为旁注,python中的类通常将其首字母大写。
你的文件应该是这样的:
main.py
import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an instance of hero
player.py
import pygame
class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()#.......etc
删除player.py中的import main
,并将main.py中的最后一行更改为:
p1 = player.hero("woody.png",[2,2])
编辑:Python不知道hero
是什么类/函数。它需要你告诉它hero是player模块中的一个类。这就是player.hero
的意思。
也永远不要从一个模块导入另一个模块,反之亦然。你可以得到一个import循环,这是很难调试的。
最后,在python中,用大写字母将类命名为Hero
而不是hero
是很常见的。