【问题标题】:Self not defined in AlienInvasion Program? [closed]未在 AlienInvasion 程序中定义自我? [关闭]
【发布时间】:2021-05-18 15:43:54
【问题描述】:

我认为导入 pygame 和 sys 模块就足够了,但事实并非如此。我知道我的代码中没有定义 self 。我正在为这个项目使用一本书,说明如下:

import pygame
import sys

class AlienInvasion:
    """Overall class to manage assets and behavior"""

def __init__(self):
    """Initiaze the game, and create the game resources."""

pygame.init()
self.screen = pygame.display.set_mode((1200, 800))

当我运行我的代码时,我得到一个未定义的错误。在我的代码下面找到:

import pygame
import sys

class AlienInvasion:
    """Overall class to manage assets and behavior"""

def __init__(self):
    """Initiaze the game, and create the game resources."""

pygame.init()
self.screen = pygame.display.set_mode((1200, 800))

这是我得到的错误:

【问题讨论】:

  • 请使用完整的错误回溯更新您的问题。
  • 您需要缩进 def __init__(self) 才能进入 AlienInvasion 类。 python中的间距很重要。见answer
  • 您需要从书中复制缩进,而不仅仅是文本。如果这实际上是代码在书中缩进的方式,那么把书扔掉 - 没用。
  • 您应该首先了解 Python 的内容之一是缩进是语法的一部分。它取代了{} 用于标记C、JavaScript 和PHP 等语言中的代码块。
  • 这段代码从不使用它定义的类或函数。

标签: python function class


【解决方案1】:

你在类结构中犯了一个错误

import pygame
import sys

class AlienInvasion:
    """Overall class to manage assets and behavior"""
   def __init__(self):
       """Initiaze the game, and create the game resources."""
       self.screen = pygame.display.set_mode((1200, 800))

测试:

AlienInvasion()

【讨论】:

    猜你喜欢
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多