Python 构造函数定义

Python 构造函数定义,python,function,python-3.x,scope,Python,Function,Python 3.x,Scope,我目前有一些代码如下: 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

我目前有一些代码如下:

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()
调用
窗口
打开窗口,我不希望在导入模块进行测试时出现这种情况

我想重新构造它,在
main
函数中包含“实际的游戏代码”,然后在
函数中执行
如果
name\uuuu==“\uuuu main\uuuuu”:main()
。然而,我不知道该怎么做

如果我只是将
#实际游戏代码开始后的代码
移动到函数中,那么
窗口
不再是全局变量,并且
打印到窗口
无法访问它

但是,将
print_to_窗口
移动到
main
函数会导致使用它的类出现相同的问题


如何重构代码?

您可以在全局级别定义名称
窗口
,然后将其分配给主函数中的对象:

window = None

def main():
    global window
    window = Window()
    # do things
    print_to_window("some text")

if __name__ == "__main__":
    main()

编辑:忘记了
main
中的“
global window
”,允许
print\u to\u window
查看修改后的
window

此伪代码没有用,特别是因为您在这两个类中的类级别调用
something()
。这真的是你在做的吗?或者你的意思是
def something(self):
在那里?@DanielRoseman不,
something
只是用来填充类主体。