【发布时间】:2014-10-14 14:41:36
【问题描述】:
我目前有一些这样的代码:
def print_to_window(text):
window.print_text(text)
do_other_stuff()
class WithMethodsThatCallprint_to_window:
something()
class ThatAlsoHasMethodsThatCallprint_to_window:
something()
# actual game code starts
window = Window()
a = WithMethodsThatCallprint_to_window()
while True:
get_input()
do_stuff()
调用Window 会打开窗口,我不希望在导入模块进行测试时发生这种情况。
我想重组它以在 main 函数中包含“实际游戏代码”,然后执行 if __name__ == "__main__": main()。但是,我不知道该怎么做。
如果我只是将#actual game code starts之后的代码移到一个函数中,那么window就不再是一个全局变量,print_to_window就不能访问了。
但是,将print_to_window 移动到main 函数中会导致使用它的类出现同样的问题。
我应该如何重构代码?
【问题讨论】:
-
这个伪代码没有用,特别是因为您在这两个类中的 class 级别调用
something()。这真的是你在做什么吗?还是你的意思是def something(self):那里? -
@DanielRoseman 不,
something只是为了填充类主体。
标签: python function python-3.x scope