简体   繁体   English

从附加模块到主模块的导入类问题

[英]Problem with import classes from additional to main module

I can't undarstand,why my class BlackChecker can't create an instance.I have 3 module.I imported 2 modules in my main module. 我无法理解,为什么我的班级BlackChecker无法创建实例。我有3个模块。我在主模块中导入了2个模块。 And NameEror raised, when i activate function in line 6 in main module. 当我在主模块的第6行中激活功能时,NameEror会升高。 I want to add !!! 我想补充! When i don't run my main program.. and copy code from main module to terminal .. ALL WORKS!!! 当我不运行我的主程序..并将代码从主模块复制到终端..所有工作!!! Also, i wan't to know how does it happen. 另外,我不知道它是如何发生的。

Module : main 模块:主

# Module : main
from class_checker import *
from blackboard import *
print(dir())

table = Board()
table.createStartPosition()
table.deck[2][5], table.deck[3][4] = table.deck[3][4], table.deck[2][5]
table.deck[5][2], table.deck[4][3] = table.deck[4][3], table.deck[5][2]

Module : class_checker 模块:class_checker

class Color():
    white=0
    black=1

class Checker():
    # PARENT CLASS

    IMG=("🅦",'🅑')

    def __init__(self,coordinate,color):
        self.color=color
        self.IMG='🅑' if color==Color.black else "🅦" # !
        self.coordinate=coordinate

    def __repr__(self):
        return self.IMG

class BlackChecker(Checker):

    list_of_black_checkers=[]

    def __init__(self,coordinate):
        super().__init__(coordinate,Color.black)

    def get_position(self):
        return self.coordinate

    @staticmethod
    def FindEnemyNear():

        HAVE_TO_CRASH =[] 

        possible_positions=( ("x+1","y-1") ,
                             ("x-1","y-1") ,
                             ("x-1","y+1") ,
                             ("x+1","y+1") , )


        ppp =              ( ("x+2","y-2") ,
                             ("x-2","y-2") ,
                             ("x-2","y+2") ,
                             ("x+2","y+2") , )

        get_figure = table.get_FigureByPosition

        for figure in BlackChecker.list_of_black_checkers:
            x,y=figure.get_position()

            if x in (2,3,4,5) and y in (2,3,4,5) :
                for pp in range(len(possible_positions)):
                    figure_after=get_figure(eval(possible_positions[pp][0]),eval(possible_positions[pp][1]))
                    if figure_after and figure_after.color == Color.white and not get_figure(eval(ppp[pp]),
                                                                                             eval(ppp[pp])):
                        HAVE_TO_CRASH.append(figure)
        return HAVE_TO_CRASH if HAVE_TO_CRASH else False

class WhiteChecker(Checker):
    def __init__(self,coordinate):
        super().__init__(coordinate,Color.white)

Module : blackboard 模块:黑板

class Board():
    def __init__(self):
       # create an empty deck
        self.deck = [[0 for i in range(8)] for i in range(8)]

    def createStartPosition(self):

        first_pos = 1  # corner position
        for raw in range(3):
            for st in range(first_pos, 8, 2):
                b = BlackChecker((raw, st))
                self.deck[raw][st] = b
                BlackChecker.list_of_black_checkers.append(b)

                w = WhiteChecker((raw, st))
                self.deck[7 - raw][7 - st] = w
        # 1

            first_pos = 1 - first_pos

    def get_FigureByPosition(self,x,y):
        return self.deck[y][x]

    def __repr__(self):
        # deck repl
        res_deck = ""
        for i in range(8):
            res_deck += " ".join(map(str, self.deck[i])) + "\n"
        return res_deck


    Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\IPython\core\interactiveshell.py", line 2961, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-3bf283b70adf>", line 1, in <module>
    runfile('C:/Users/user/Desktop/ооп/Programs/Checkers/main.py', wdir='C:/Users/user/Desktop/ооп/Programs/Checkers')
  File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/user/Desktop/ооп/Programs/Checkers/main.py", line 7, in <module>
    table.createStartPosition()
  File "C:\Users\user\Desktop\ооп\Programs\Checkers\blackboard.py", line 14, in createStartPosition
    b = BlackChecker((raw, st))
NameError: name 'BlackChecker' is not defined

您应该将“ class_checker”导入“黑板”模块中,因为在那里不可见

You need to import class_checker module in blackboard.py and change to the following in blackboard.py; 您需要在class_checker中导入class_checker模块,并在class_checker中更改为以下内容;

b = class_checker.BlackChecker((raw,st))

class_checker.BlackChecker.list_of_black_checkers.append(b)

w = class_checker.WhiteChecker((raw, st))

Your py file should look like this; 您的py文件应如下所示;

import class_checker

class Board():
    def __init__(self):
        # create an empty deck
        self.deck = [[0 for i in range(8)] for i in range(8)]

    def createStartPosition(self):

        first_pos = 1  # corner position
        for raw in range(3):
            for st in range(first_pos, 8, 2):
                b = class_checker.BlackChecker((raw,st))
                self.deck[raw][st] = b
                class_checker.BlackChecker.list_of_black_checkers.append(b)

                w = class_checker.WhiteChecker((raw, st))
                self.deck[7 - raw][7 - st] = w
            # 1

            first_pos = 1 - first_pos

    def get_FigureByPosition(self,x,y):
        return self.deck[y][x]

    def __repr__(self):
        # deck repl
        res_deck = ""
        for i in range(8):
            res_deck += " ".join(map(str, self.deck[i])) + "\n"
        return res_deck

You can also use from class_check import * at the top of the .py and leave the class_checker off of the other parts of the code, but in my opinion it is more readable to clairfy which module it is coming from. 您也可以在.py顶部使用from class_check import * ,而将class_checker保留在代码的其他部分之外,但是我认为更清晰地知道它来自哪个模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM