【问题标题】:How can I create a subclass of an existing class?如何创建现有类的子类?
【发布时间】:2018-02-17 19:57:36
【问题描述】:

我正在使用 PyGame 创建一个 Space Invaders,并且我想创建 Alien 类的子类,以简化我的代码。我该怎么做?这是我到目前为止的代码:

class Alien(pygame.sprite.Sprite):
    def __init__(self, width, height):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(RED)
        self.image = pygame.image.load("alien1.png").convert_alpha()
        self.rect = self.image.get_rect()

【问题讨论】:

标签: python-3.x pygame subclass


【解决方案1】:

事实上,您刚刚创建了 Sprite 的一个子类。只需对 Alien 执行相同操作即可。

class Reptilian(Alien):
    def __init__(self, width, height, human_form):  # you can pass some other properties
        super().__init__(width, height)  # you must pass required args to Alien's __init__
        # your custom stuff:
        self.human_form = human_form

【讨论】:

  • 非常感谢,我现在明白了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2010-12-09
相关资源
最近更新 更多