【问题标题】:How to inherit a pygame class?如何继承一个pygame类?
【发布时间】:2018-09-17 00:31:08
【问题描述】:

当我运行这段代码时(这是当前的整个代码,即只有 3 行):

import pygame
class sp(pygame.sprite):
    pass

我明白了:

TypeError: module() takes at most 2 arguments (3 given)

我想继承这个类来为它创建一些额外的对象,以及执行一些已经存在的功能。

例如,而不是...

mysprites = pygame.sprite.Group()

我想要……

mysprites = sp.Group()

我该怎么做?

【问题讨论】:

  • 当您继承 sprite 时,您是否覆盖了 __init__ 方法?如果可以,您可以显示该代码吗?
  • @101,我现在把整个代码,也就是3行...
  • 等等,sprite 是一个模块,而不是一个类,所以你不能继承它。不过,您可以将 sprite 中的所有内容导入到新模块中。

标签: python python-3.x class inheritance pygame


【解决方案1】:

正如@101 在评论中提到的,spritepygame [sub] 模块,但它本身并不是 Python class。要做你想做的事,你需要从模块定义的Sprite 类派生你的子类。这意味着使用以下内容。 (pygame documentation 中还有一个示例,说明创建 Sprite 子类的方式略有不同,您可能应该看看。)

还要注意,根据PEP 8 - Style Guide for Python Code 的命名约定部分,类名的首字母应该大写,所以我也修复了这个问题。

from pygame.sprite import Sprite

class Sp(Sprite):
    pass

回答您尝试使用sp.Group() 的问题的另一部分。问题是您尝试做的事情完全不正确。 Group 是一个单独的“容器”类,它也在 pygame.sprite 模块中定义。将一组Sprite 类实例分组是主要目的。它应该能够很好地处理您的 Sprite 子类。下面是更多代码,展示了如何做到这一点:

from pygame.sprite import Group, Sprite

class Sp(Sprite):
    pass

# Create a Group container instance and put some Sp class instances in it.
mygroup = Group()
sp1 = Sp()  # Create first instance of subclass.
mygroup.add(sp1)  # Put it in the Group (NOT via sp1.Group())

sp2 = Sp()  # Create another instance of subclass.
mygroup.add(sp2)  # Put it into the Group, too.

【讨论】:

  • 好的,但是如何执行当前对象“组”? mysprites = Sp.Group()
  • 我的回答的最新更新也解决了您问题的这方面。另见How to use sprite groups in pygame
猜你喜欢
  • 2014-11-22
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 2021-11-30
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多