繁体   English   中英

从 Python 中的另一个文件导入类

[英]Importing classes from another file in Python

我最近开始学习 Pygame(一个 Python 模块)。 我的 Pygame 项目现在变得相当冗长 - 以至于难以导航。 使用以前的 python 项目,我已经能够将大部分功能简单地存储在单独的 python 文件中,然后将其导入主文件。

例如,在主文件中:

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
import second_file
second_file.run()

在第二个文件中:

def run():
   screen.fill([0, 255, 255])

I want to store a function in the second file, but this function needs to be able to interact with the same Pygame window as the main file. 当前尝试执行此操作时,它会返回一条错误消息,告诉我未定义主文件屏幕的名称。

任何有关如何解决此问题的帮助将不胜感激!

有多种方法可以做这样的事情。 可能最好的方法是将屏幕作为参数传递给 function ,如下所示:

def run(screen):
   screen.fill((0, 255, 255))

主要是:

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
import second_file
second_file.run(screen)

或者,您基本上可以将屏幕设为全局并从主文件中导入 但我不推荐这种方法。 如果您确实选择了这种方法,请注意循环导入(主要从 second_file 导入和 second_file 从 main 导入)。

暂无
暂无

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

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