For loop printing memory location of class instead

2019-03-04 16:19发布

问题:

I have some code which seems to print [<__main__.TCar object at 0x0245C1B0>] but I want it to print the actual contents of the list.

class TCar():
  def __init__(self, Make, Model, EngineSize, Price):
    self.Make = str(Make)
    self.Model = str(Model)
    self.EngineSize = float(EngineSize)
    self.Price = float(Price)

Garage = []

for i in range(5):
  Make = input("Please enter the make of the car: ")
  Model = input("Please enter the model of the car: ")
  EngineSize = input("Please enter the engine size of the car: ")
  Price = input("Please enter the price of the car: ")
  Garage.append(TCar(Make, Model, EngineSize, Price))
  print(Garage)

What is wrong with my code?

回答1:

You have to define either a __str__ method or a __repr__ method for that:

class TCar():
  def __init__(self, Make, Model, EngineSize, Price):
    self.Make = str(Make)
    self.Model = str(Model)
    self.EngineSize = float(EngineSize)
    self.Price = float(Price)

  def __repr__(self):
    return "<Car {0} {1} {2} {3}>".format(self.Make, self.Model, self.EngineSize, self.Price)

  def __str__(self):
    return "{0} {1}".format(self.Make, self.Model)

In a nutshell,

__repr__ is used if there's a need to display "raw" content of the object, it's the kind you see when you are displaying the list's contents, so if you have a list of cars, it would look like this:
[<Car Tesla Model S 500bhp $100000>, <Car Smart Fortwo 80bhp $5000>]

__str__ is used if you try to print the actual object, like print(TeslaCar) with TeslaCar being a TCar instance. It would give you something like "Tesla Model S".



回答2:

You have a list of objects here. Add something like:-

def __str__(self):
  print self.Make, self.Model, self.EngineSize, self.Price

This would print the value of all attributes of object. Or you can modify the function as per your behavior requirement.



回答3:

print the attribute one by one rather than printing garange once: print(self.attribute).Note that the attribute in the code is an instance of the object



回答4:

You can either override __str__ or __repr__ like this:

class TCar():
  def __init__(self, Make, Model, EngineSize, Price):
    self.Make = str(Make)
    self.Model = str(Model)
    self.EngineSize = float(EngineSize)
    self.Price = float(Price)

  def __repr__(self):
    return "{Make}-{Model} (v{EngineSize}/{Price}$)".format(**self.__dict__)

Garage = [TCar("Audi", "TT", "8", "80000")]
print(Garage)
# [Audi-TT (v8.0/80000.0$)]

Also you might want to check out this question about __str__ vs. __repr__.