【发布时间】:2017-02-08 10:17:23
【问题描述】:
对于棋盘,假设有一个 Board 类,具有 squares 属性,这是一个 Square 实例数组。文件结构是有main.py、board.py、square.py和一个空的__init__.py(我不得不说我不完全理解后者的目的......但显然这就是做事)。这些都在同一个目录中。 (我之前没有在 Python 中做过任何涉及多个文件的事情。)
在main.py 中,我想实例化一个Board 对象。这是main.py的内容:
from board import Board
from square import Square
board = Board()
这里是square.py:
class Square:
def __init__(self):
pass
#this class doesn't do anything yet
这里是board.py:
class Board:
row_count = 8
column_count = 8
def __init__(self):
self.squares = self.generate_squares()
def generate_squares(self):
squares = {}
for i in range(0, self.row_count * self.column_count):
squares[i] = Square()
return squares
但是,当我运行main.py 时,我被告知squares[i] = Square() 行有错误;即NameError: global name 'Square' is not defined。
我已尝试将其更改为 squares[i] = square.Square(),但这会产生相同的错误。
如果我删除 import 语句并将类定义复制到 main.py 中,则实例化工作正常,从而将问题归结为与 import 语句本身相关。
【问题讨论】:
-
使用堆栈跟踪找出问题所在..
-
如果你在那里使用它,你也必须在
board.py中使用from square import Square。
标签: python class namespaces python-import