我遇到了使用Python继承类的问题

时间:2013-03-31 02:16:06

标签: python class inheritance

我正在创建一个游戏,你在屏幕的底部有一艘船,你正在拍摄从屏幕顶部掉落的岩石点。有两种类型的岩石从天而降,大小不一。我决定使用1类作为Rock,并将两个def标记为smallRock和bigRock。我以为我在主程序中有代码,但我一直在收到错误。 这是我用于Rock Class的代码:

class Rock(pygame.sprite.Sprite):
    def __init__(self,bigRock,smallRock):
        pygame.sprite.Sprite.__init__(self)
        self.width = 20
        self.height = 20
        self.x_change = 0
        self.y_change = yChange
        self.image.set_colorkey([255,255,255])
        self.rect = self.image.get_rect()
        self.rect.left = x
        self.rect.top = y

    def bigRock(self):
        self.image = pygame.image.load('rockLarge.png').convert()

    def smallRock(self):
        self.image = pygame.image.load('rockSmall.png').convert()

以下是主程序的代码块:

# How many big rocks falling------------------

    Rock = pygame.sprite.RenderPlain()
    bigRockRandomizer = rockRandomizer
    bigRockQuantity = 0
    while bigRockQuantity < bigRockRandomizer:
        bigRockXLocation = xLocation
        brock = Rock.bigRock(black,bigRockXLocation)
        Rock.bigRock.add(brock)
        bigRockQuantity = bigRockQuantity + 1

# How many small rocks falling-----------------

    Rock = pygame.sprite.RenderPlain()
    smallRockRandomizer = rockRandomizer
    smallRockQuantity = 0
    while smallRockQuantity < smallRockRandomizer:
        smallRockXLocation = xLocation
        srock = smallRock(black,smallRockXLocation)
        smallRock.add(srock)
        smallRockQuantity = smallRockQuantity + 1

以下是我得到的当前错误代码:

Traceback (most recent call last):
  File "C:\Users\Steve\Desktop\Project April\Alien Metor Storm v1_5\main.py", line 561, in <module>
    main()
  File "C:\Users\Steve\Desktop\Project April\Alien Metor Storm v1_5\main.py", line 58, in main
    brock = Rock.bigRock(black,bigRockXLocation)
AttributeError: 'Group' object has no attribute 'bigRock'

有人能告诉我我做错了什么并指出我回到了正确的轨道?

1 个答案:

答案 0 :(得分:1)

Rock = pygame.sprite.RenderPlain() # OOPS: Overwrote class name Rock

    brock = Rock.bigRock(black,bigRockXLocation) ## OOPS: Even if Rock was still the class, this call is invalid because bigRock is an instance method.

我建议您尝试子类而不是在Rock中创建方法。像

这样的东西
class Rock:
    def __init__(self, imagefn):
        self.image = pygame.image.load(imagefn).convert()
        ...

class BigRock(Rock):
    def __init__(self):
        Rock.__init__(self, 'rockLarge.png')

class SmallRock(Rock):
    def __init__(self):
        Rock.__init__(self, 'rockSmall.png')

然后根据需要制作BigRockSmallRock个实例。