【问题标题】:snake game - str object is not callable蛇游戏 - str 对象不可调用
【发布时间】:2018-05-30 19:43:49
【问题描述】:

对不起,如果答案很简单,但我真的坚持这个...... 我正在尝试制作“蛇游戏”,但是当我尝试调用该函数以使蛇移动时出现错误。 错误状态:

    Traceback (most recent call last):
  File "C:\Users\Fran\Desktop\SnakeISN.py", line 89, in <module>
    theApp.on_execute()
  File "C:\Users\Fran\Desktop\SnakeISN.py", line 80, in on_execute
    snake.changeDirectionTo(3)
TypeError: 'str' object is not callable

每当我开始按箭头键时... 导入pygame 导入系统 随机导入

class Snake():
    def __init__(self):
     self.x=400
     self.y=590
     self.direction = "RIGHT"
     self.changeDirectionTo = self.direction

    def changeDirectionTo(self,dir):
     if dir == 1 and not self.direction == 2:
         self.direction = "RIGHT"
     if dir == 2 and not self.direction == 1:
         self.direction = "LEFT"
     if dir == 3 and not self.direction == 4:
         self.direction = "UP"
     if dir == 4 and not self.direction == 3:
         self.direction = "DOWN"

    def move(self, foodPos):
     if self.direction == "RIGHT":
         self.x += 100
     if self.direction == "LEFT":
         self.x -= 100
     if self.direction == "UP":
         self.y -= 100
     if self.direction == "DOWN":
         self.y += 100

class Appli:

    windowX = 800
    windowY = 600

    def __init__(self):
        self._running = True
        self._show_surf = None
        self._image_surf = None
        self.snake = Snake() 

    def on_init(self):
        pygame.init()
        self._show_surf = pygame.display.set_mode((self.windowX,self.windowY), pygame.HWSURFACE)

        pygame.display.set_caption('Snake V2.7')
        self._running = True
        self._image_surf = pygame.image.load("pygame.png").convert()


    def on_event(self, event):
        if event.type == QUIT:
            self._running = False

    def on_loop(self):
        pass

    def on_render(self):
        self._display_surf.fill((0,0,0))
        self._display_surf.blit(self._image_surf,(self.snake.x,self.snake.y))
        pygame.display.flip()

    def on_cleanup(self):
        pygame.quit()

    def on_execute(self):
        snake=Snake()
        if self.on_init() == False:
            self._running = False

        while( self._running ):
            pygame.event.pump()
            action = pygame.key.get_pressed()
            if action[pygame.K_RIGHT]:
                snake.changeDirectionTo(1)
            if action[pygame.K_LEFT]:
                snake.changeDirectionTo(2)
            if action[pygame.K_UP]:
                snake.changeDirectionTo(3)
            if action[pygame.K_DOWN]:
                snake.changeDirectionTo(4)
            self.on_loop()
            self.on_render()
        self.on_cleanup()


if __name__ == "__main__" :
    theApp = App()
    theApp.on_execute()

有人知道问题出在哪里吗? 第一次遇到这个错误时,我将所有方向 "RIGHT" 、 "LEFT" 、 "UP" 、 "DOWN" 改为 1,2,3,4 ,希望它能解决 'str call' 错误,但它没有……

感谢您的帮助

【问题讨论】:

    标签: python string


    【解决方案1】:

    了解错误信息是解决问题的关键。

    当你调用一个函数时,你添加括号和任何参数:

    >>> def func():
    ...     print('worked!')
    ...
    >>> func()
    worked!
    

    但是当你给不是函数的东西添加括号时会发生什么?

    >>> func = 1
    >>> func()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not callable
    
    >>> func = 'abc'
    >>> func()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object is not callable
    

    所以您的错误表明您尝试调用的函数 (changeDirectionTo(3)) 不是函数,而是字符串。

    由于您有 def changeDirectionTo 行将其声明为函数,因此请查找覆盖此定义的 changeDirectionTo 的其他用途。

    问题出在def __init__。这两行声明一个字符串,然后将其分配给changeDirectionTo,覆盖之前的函数定义。

     self.direction = "RIGHT"
     self.changeDirectionTo = self.direction
    

    使用不同的变量名或删除该行来解决问题。

    【讨论】:

    • 谢谢你,我现在明白了 :)
    • 很高兴听到这个消息!如果答案对您有用,请考虑对其进行投票。您还可以选择一个答案是最好的,方法是在左侧用绿色复选标记排除它
    【解决方案2】:

    在您的蛇的__init__ 方法中,您定义了一个属性self.changeDirectionTo,它指向一个字符串并覆盖具有相同名称的方法。

    你应该删除那行。

    【讨论】:

    • 解决了我的问题。非常感谢!
    【解决方案3】:

    从您的 __init__ 方法中删除此行:

    self.changeDirectionTo = self.direction
    

    你已经把函数changeDirectionTo 变成了一个字符串...

    【讨论】:

      【解决方案4】:

      删除

       self.changeDirectionTo = self.direction
      

      你用相同的名字命名一个方法和实例变量来隐藏方法

      class Hello:
          def __init__(self):
              self.hello = 'hello instance variable'
      
          def hello(self):
              print('hello')
      
      h = Hello()
      print(h.hello)  # print out hello instance variable
      print(h.hello())  # throw the error you got  TypeError: 'str' object is not callable
      

      【讨论】:

        猜你喜欢
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多