导入错误:难以从另一个文件(在同一目录中)导入类

时间:2020-06-25 17:53:05

标签: python

我正在尝试从p_class.py导入“计算机类”。它们在同一个目录中,我也有一个__init__.py,但是我仍然收到导入错误。我尝试了几种在线上看到的书写方式(并添加了__init__.py文件),但我掌握的知识很有限,似乎无法理解它的问题所在。 / p>

编辑:错误消息:'无法导入'p_class'

如果从.py_class导入计算机:

”追踪(最近一次通话结束): 文件“ / Users /用户名/Documents/Python/Scripts/game/game.py”,第2行 从.p_class导入计算机 ImportError:尝试相对导入,但没有已知的父包”

import random
from p_class import Computer

player_health = 100
comp_health = 100

def c_moves(n, h1, h2): # pass in player input / comp random number (player input will need int()) /// h = player_health or comp_health
    if n == 1:
        print('... used light attack')
        attack_strength = random.randint(18,25) # get attack strength
        
        
        l = random.randint(1,6)  # check to see if attack lands
        if l == 1:       # attack missed 5 dmg to self
            print('You missed, fell and hit yourself for 5 dmg')
            h1 = h1 - 5
        elif l == 2:
            print('You missed')
        
        elif l in [3, 4, 5, 6]:
            print('Attack landed\nh2 took: {} dmg'.format(attack_strength))

            # check to see if the opposing player gets a retaliation

下面是p_class.py文件

import random

class Computer:
    def __init__(self, name, health):
        self.name = self.get_name()
        self.health = 100

    def get_name(self):
        n = open('/Users/saeley_07/Documents/Python/Scripts/Pokemon/p_names.txt')

        read_txt = True
        while read_txt:
            line = next(n)
            for num, aline in enumerate(n, 2):
                    
                if random.randrange(num): continue
                line = aline

                if line == "\n" or "":
                    continue
                
                else:
                    read_txt = False
                    return line
        n.close()

# n = Computer.get_name(0)
# print(n)

目录结构:

Documents
-----Python
-------Python Scripts
----------game
------------main.py
------------p_class.py

0 个答案:

没有答案