[英]Structuring function definitions
I currently have some code like this: 我目前有一些这样的代码:
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()
Calling Window
opens the window, which I don't want to happen when I import the module for testing. 调用
Window
打开一个窗口,当我导入模块进行测试时,我不想发生这种情况。
I'd like to restructure this to have the "actual game code" in a main
function, and then do if __name__ == "__main__": main()
. 我想对其进行重组,以使
main
函数中具有“实际游戏代码”,然后执行if __name__ == "__main__": main()
。 However, I can't work out how to do this. 但是,我不知道如何做到这一点。
If I just move the code after #actual game code starts
into a function, then window
is no longer a global variable, and print_to_window
can't access it. 如果我只是在
#actual game code starts
到函数中之后才移动代码,则window
不再是全局变量,并且print_to_window
无法访问它。
However, moving print_to_window
into the main
function causes the same problem with the classes that use it. 但是,将
print_to_window
移至main
函数会导致与使用它的类相同的问题。
How should I restructure the code? 我应该如何重组代码?
You can define the name window
at the global level, then assign it to an object in the main function: 您可以在全局级别定义名称
window
,然后将其分配给main函数中的对象:
window = None
def main():
global window
window = Window()
# do things
print_to_window("some text")
if __name__ == "__main__":
main()
Edit: forgot the " global window
" in main
, allowing print_to_window
to see the modified window
. 编辑:忘记了
main
的“ global window
”,允许print_to_window
查看修改后的window
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.