“从文件导入类”也尝试导入其他类

时间:2020-04-04 16:08:12

标签: python class import

我试图通过制作一个游戏来学习python,并且试图将我的d5游戏文件中的部队类导入到当前的文件中。此类仅包含变量,我想在两个文件中都使用它们:

import pygame as pg
import random as rd
import sys
sys.path.append('C:/Users/hornu/OneDrive/Dungeon')
from d5 import troops

这是应该导入的类:

class troops:

    Goblins=[3,0,7,1,'small','living',['scout'],False,['Goblin','Goblins']]
    Skeletons=[6,4,3,2,'normal','undead',[None],False,['Skeleton','Skeletons']]
    Ogres=[9,0,19,3,'large','living',[None],False,['Ogre','Ogres']]
    Demons=[10,2,13,3,'normal','magical',[None],False,['Demon','Demons']]
    Bosses=[20,3,35,5,'large','living',[None],False,['Boss','Bosses']]

    Peasants=[1,0,9,1,'normal','undead',[None],False,['Peasant','Peasants']]
    Militia=[4,1,9,2,'normal','living',[None],False,['Militiaman','Militiamen']]
    Squires=[6,1,12,3,'normal','living',['scout'],False,['Squire','Squires']]
    Knights=[10,3,15,3,'normal','living',[None],False,['Knight','Knights']]
    Paladins=[15,3,15,4,'normal','living',[None],False,['Paladin','Paladins']]

我的问题是,导入部队类后,它将继续从文件中导入其他类,并进入第二个文件中声明的导入,直到到达无法导入的类为止(因为它在第三个文件中)没有提供路径),然后退出并显示错误。据我所知,我想要的类已正确导入,我只是不明白为什么它继续导入其他内容。 我敢肯定,我还不完全了解导入的工作原理,但是它还在继续下去似乎很奇怪。如何获取仅导入单个类并停止的信息?还是应该为此使用完全不同的方法?

谢谢!

1 个答案:

答案 0 :(得分:0)

当您想从脚本中导入特定内容时,对于Function而言,对于Class而言,导入效果更好。因此,尝试使用:

def troops():

    return [[3,0,7,1,'small','living',['scout'],False,['Goblin','Goblins']]
    ,[6,4,3,2,'normal','undead',[None],False,['Skeleton','Skeletons']]
    ,[9,0,19,3,'large','living',[None],False,['Ogre','Ogres']]
    ,[10,2,13,3,'normal','magical',[None],False,['Demon','Demons']]
    ,[20,3,35,5,'large','living',[None],False,['Boss','Bosses']]
    ,[1,0,9,1,'normal','undead',[None],False,['Peasant','Peasants']]
    ,[4,1,9,2,'normal','living',[None],False,['Militiaman','Militiamen']]
    ,[6,1,12,3,'normal','living',['scout'],False,['Squire','Squires']]
    ,[10,3,15,3,'normal','living',[None],False,['Knight','Knights']]
    ,[15,3,15,4,'normal','living',[None],False,['Paladin','Paladins']]]

现在使用:

from d5 import troops
Goblins,Skeletons,Ogres,Demons,Bosses,Peasants,Militia,Squires,Knights,Paladins=troops()