我是python的初学者,我想问一下,我有2个模块,并且我想从一个模块获取值到另一个模块。我想获取“ ids”值,并在另一个模块中使用它以在屏幕上打印 我试图从导入中调用它,但是它不起作用,我迷路了
Class CoordinatesGenerator: KEY_RESET = ord(“ r”) KEY_QUIT = ord(“ q”)
def __init__(self, image, output, color):
self.output = output
self.caption = image
self.color = color
self.image = open_cv.imread(image).copy()
self.click_count = 0
self.ids = 0
self.coordinates = []
open_cv.namedWindow(self.caption, open_cv.WINDOW_GUI_EXPANDED)
open_cv.setMouseCallback(self.caption, self.__mouse_callback)
def generate(self):
while True:
open_cv.imshow(self.caption, self.image)
key = open_cv.waitKey(0)
if key == CoordinatesGenerator.KEY_RESET:
self.image = self.image.copy()
elif key == CoordinatesGenerator.KEY_QUIT:
break
open_cv.destroyWindow(self.caption)
def __mouse_callback(self, event, x, y, flags, params):
if event == open_cv.EVENT_LBUTTONDOWN:
self.coordinates.append((x, y))
self.click_count += 1
if self.click_count >= 4:
self.__handle_done()
elif self.click_count > 1:
self.__handle_click_progress()
open_cv.imshow(self.caption, self.image)
def __handle_click_progress(self):
open_cv.line(self.image, self.coordinates[-2], self.coordinates[-1], (255, 0, 0), 1)
def __handle_done(self):
open_cv.line(self.image,
self.coordinates[2],
self.coordinates[3],
self.color,
1)
open_cv.line(self.image,
self.coordinates[3],
self.coordinates[0],
self.color,
1)
self.click_count = 0
coordinates = np.array(self.coordinates)
self.output.write("-\n id: " + str(self.ids) + "\n coordinates: [" +
"[" + str(self.coordinates[0][0]) + "," + str(self.coordinates[0][1]) + "]," +
"[" + str(self.coordinates[1][0]) + "," + str(self.coordinates[1][1]) + "]," +
"[" + str(self.coordinates[2][0]) + "," + str(self.coordinates[2][1]) + "]," +
"[" + str(self.coordinates[3][0]) + "," + str(self.coordinates[3][1]) + "]]\n")
draw_contours(self.image, coordinates, str(self.ids + 1), COLOR_WHITE)
for i in range(0, 4):
self.coordinates.pop()
self.ids += 1
答案 0 :(得分:0)
将代码放入名为myclasses.py的(python)文件中,并从同一位置创建另一个文件,您将以如下方式导入(myclasses.py)模块:
from myclasses import CoordinatesGenerator
请不要忘记将一个名为__init__.py
的文件添加到此文件夹,以便Python知道它为目录。否则,您的导入将失败!
结论:
您尝试导入模块的每个文件夹都需要一个__init__.py
文件。因此,在上面的示例中,您将有一个包含3个文件的文件夹