1

When i try to put my objects into a list, i can not get an output with object names, it gives a weird output like "_ main _.object at 0x029E7210". I want to select my objects randomly to blit ONE of them onto the screen. But i could not figure this out.

car_main = pygame.image.load("car_main.png")
car_red_ = pygame.image.load("car_red.png")
car_blue = pygame.image.load("car_blue.png")

class cars:

    def __init__(self,x,y,car_type,w=50,h=100,s=5):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.s = s
        self.car_type = car_type

    def draw(self):
        dp.blit(self.car_type,(self.x,self.y))

car1 = cars(x,y,car_main)
car2 = cars(x,y,car_red)
car3 = cars(x,y,car_blue)
car_list = [car1,car2,car3]
rc = random.choice(car_list)
print(rc)

# output>  __main__.object at 0x02A97230

When I change

car_list = [car1,car2,car3] with;
car_list = [car1.car_type,car2.car_type,car3.car_type]

# output > Surface(50x100x32 SW)

But I want to see an output as my object names. Not as a string type ("car_main"). I want to get an output as the object name (car_main) directly. Because in the main loop, i will choose one of them to blit onto the screen everytime when the loop renews itself.

knh190
  • 2,744
  • 1
  • 16
  • 30
Arda Altun
  • 137
  • 1
  • 2
  • 9

2 Answers2

2

You need to define __str__ for your class Car to let it properly handle object to string:

class Car:

    def __str__(self):
        for k, var in globals().items():
            if var == self:
                return k
        # default
        return "Car"

Note1: Usually use uppercased Car for a class and car for an instance.


Note2: Look up variable strings in globals is not reliable. You may not want to make all variables global, and manually search them in scope is tedious. Actually why don't you give your Car a name attribute? Then you nicely have:

class Car:

    def __init__(self, name):
        self.name=name

    def __str__(self):
        return self.name

car = Car(name='first car')
print(car) # 'first car'

More read about "magic methods": https://rszalski.github.io/magicmethods/#representations

knh190
  • 2,744
  • 1
  • 16
  • 30
  • i just added "name" into the __init__ method. and i called my object (car1 = cars("car_red",x,y,car_type) and it gives the name. should i add __str__ ? because it seems like it works currently – Arda Altun Mar 26 '19 at 10:42
  • @ArdaAltun Well, not 100% sure with your current code, but you should solve the perplex after reading the referenced link. It explains why/when you should define `__str__()` – knh190 Mar 26 '19 at 14:24
0

Add a __str()__ magic method to your car class like so:

def __str__(self):
    return f'car with x of {self.x}, y of {self.y}, and type of {self.car_type}'
Alec
  • 8,529
  • 8
  • 37
  • 63