在if\uu name\uuuu=='\uu main\uuuu':b中指定自变量很麻烦

2024-05-23 18:09:52 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行程序时,我希望它运行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

Tags: thenameinfrompyimportselfgame
2条回答

似乎代码中存在缩进错误:if __name__ == '__main__':是在类中定义的。如果希望在导入文件/模块时执行它,则需要在该文件/模块的global命名空间(意思是:没有缩进)的类外部定义它

实例本身是自动传递的。使用以下选项:

the_controls = Controls()
the_controls.start_game()

这与您可能熟悉的其他对象方法类似:

'hello world'.upper()

你也可以这样写:

the_controls = Controls()
Controls.start_game(the_controls)

或者这个:

str.upper('hello world')

但前者比后者更受欢迎

相关问题 更多 >