Doritito
Doritito

Reputation: 77

Access objects stored in list

I´m not sure if I have done everything correctly but I want to access objects that I stored in a list. Here is the code:

# Obstcale class
class obstacle(object):

    def __init__(self, obstacleImg, obstacleX, obstacleY, obstacelX_change):
        self.obstacleImg = pygame.image.load("rock.png")
        self.obstacleX = random.randint(600, 700)
        self.obstacleY = random.randint(0, ScreenHeight - 64)
        self.obstacleX_change = -0.3

    def spawn_obstacle(self, x, y):
        screen.blit(self.obstacleImg, (x, y))
while running:

    if count < 1299:
        count += 1
    else:
        obstacle_number += 1
        obstacle_list.append(obstacle)
        count = 0
        print(obstacle_list[obstacle_number-1])       

With the print function I want to print out every new object created by accessing the List but everything i get is this:

<class '__main__.obstacle'>
<class '__main__.obstacle'>
<class '__main__.obstacle'>
<class '__main__.obstacle'>
<class '__main__.obstacle'>
<class '__main__.obstacle'>

Upvotes: 1

Views: 484

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177610

Create actual instances of your class. Defining a __repr__ (debug representation) to make a meaningful display of the instance helps, too. Below is your code modified into a minimal, reproducible example creating a short list of Obstacles:

import random

ScreenHeight = 600

class Obstacle(object):

    def __init__(self): # removed unused parameters
        self.obstacleImg = 'rock.png' # pygame.image.load("rock.png")
        self.obstacleX = random.randint(600, 700)
        self.obstacleY = random.randint(0, ScreenHeight - 64)
        self.obstacleX_change = -0.3

    def __repr__(self):
        return f'Obstacle(image={self.obstacleImg!r}, X={self.obstacleX}, Y={self.obstacleY}, change={self.obstacleX_change})'
    
obstacle_list = []
while len(obstacle_list) < 5:
    obstacle = Obstacle()  # call the class to create an instance
    obstacle_list.append(obstacle)
    print(obstacle)
Obstacle(image='rock.png', X=650, Y=62, change=-0.3)
Obstacle(image='rock.png', X=677, Y=8, change=-0.3)
Obstacle(image='rock.png', X=625, Y=370, change=-0.3)
Obstacle(image='rock.png', X=642, Y=536, change=-0.3)
Obstacle(image='rock.png', X=688, Y=311, change=-0.3)

Upvotes: 1

Related Questions