当我运行程序时,我希望它运行start_game(self)
。为此,必须运行构造函数。否则,对象就不存在,因此它们的方法就无法运行。到目前为止,很清楚。基本上,我很难正确地“开始”这个过程
from Surface import Surface
from Pellet import Pellet
from Pacman import Pacman
from Ghost import Ghost
from Timer import Timer
class Controls:
def __init__(self):
global the_surface
the_surface = Surface(self)
the_pellets = []
for y in range(0, 8):
for x in range(0, 14):
pellet = Pellet(x, y)
the_pellets.append(pellet)
global the_pacman
the_pacman = Pacman(the_pellets)
the_ghosts = []
for ghost in range(0, 3):
the_ghosts.append(Ghost())
global the_timer
the_timer = Timer(self, 200)
# [...]
def start_game(self):
self.__init_game_objects()
Timer.start(the_timer)
return
def tick_timer(self):
Pacman.move(the_pacman)
return
# http://stackoverflow.com/a/419185
if __name__ == '__main__':
# need to run start_game()
我尝试过的(以下所有内容都在if __name__ [...]
行之后,每个项目符号代表一次尝试。)
第一次尝试:
the_controls = Controls()
the_controls.start_game(the_controls)
Traceback (most recent call last):
File "Controls.py", line 8, in <module>
class Controls:
File "Controls.py", line 53, in Controls
the_controls = Controls()
NameError: name 'Controls' is not defined
第二次尝试:
__init__('Controls')
self.start_game(self)
Traceback (most recent call last):
File "Controls.py", line 8, in <module>
class Controls:
File "Controls.py", line 54, in Controls
self.start_game(self)
NameError: name 'self' is not defined
第三次尝试(由@TigerhawkT3建议)
the_controls = Controls()
the_controls.start_game()
Traceback (most recent call last):
File "Controls.py", line 8, in <module>
class Controls:
File "Controls.py", line 53, in Controls
the_controls = Controls()
NameError: name 'Controls' is not defined
似乎代码中存在缩进错误:
if __name__ == '__main__':
是在类中定义的。如果希望在导入文件/模块时执行它,则需要在该文件/模块的global
命名空间(意思是:没有缩进)的类外部定义它实例本身是自动传递的。使用以下选项:
这与您可能熟悉的其他对象方法类似:
你也可以这样写:
或者这个:
但前者比后者更受欢迎
相关问题 更多 >
编程相关推荐