Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

python - Why is a pygame.Surface object not subscriptable inside a class?

So I have a list of images to be indexed inside a class.

Code with error:

imgs = [pygame.image.load("myimg1.png"), pygame.image.load("myimg2.png"), pygame.image.load("myimg3.png")]

class ParentClass:
    def __init__(self, imgs, coordinates):
        self.imgs = imgs
        self.index = 0
        self.activeImg = imgs[self.index]
        self.x, self.y = coordinates

class ChildClass(ParentClass):
    def __init__(self, imgs, coordinates):
        super().__init__(imgs, coordinates)
        #more stuff

child = ChildClass(imgs, (100, 100))

Error:

TypeError: 'pygame.Surface' object is not subscriptable

Code without error: (Not what I want)

imgs = [pygame.image.load("myimg1.png"), pygame.image.load("myimg2.png"), pygame.image.load("myimg3.png")]

class ParentClass:
    def __init__(self, imgs, startImg, coordinates):
        self.imgs = imgs
        self.index = 0
        self.activeImg = startImg
        self.x, self.y = coordinates

class ChildClass(ParentClass):
    def __init__(self, imgs, coordinates):
        super().__init__(imgs, imgs[0], coordinates)
        #more stuff

child = ChildClass(imgs, (100, 100))

I don't understand why that error comes in my main code. As far as I'm aware, this list of images should be indexed without any errors. Python seems to be thinking I'm indexing through the pygame.Surface object (clearly not what I'm doing). But on the other hand, when I pass it as a parameter, it runs without any errors (which is what I find quite confusing).

Help will be appreciated. Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...