簡體   English   中英

在__name__ =='__main__'的情況下無法指定自變量:

[英]trouble to specify the self variable in if __name__ == '__main__': block

當我運行程序時,我希望它運行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

實例本身會自動傳遞。 使用以下內容:

the_controls = Controls()
the_controls.start_game()

這類似於您可能熟悉的其他對象方法:

'hello world'.upper()

您也可以這樣寫:

the_controls = Controls()
Controls.start_game(the_controls)

或這個:

str.upper('hello world')

但是前者比后者更受歡迎。

似乎您的代碼中有一個縮進錯誤: if __name__ == '__main__':在您的類中定義。 如果要在導入文件/模塊時執行它,則需要在該文件/模塊的global命名空間的類之外定義它(意味着:不帶縮進)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM