用于循环打印类的内存位置而不是列表 [英] For loop printing memory location of class instead of list

查看:64
本文介绍了用于循环打印类的内存位置而不是列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码似乎可以打印 [< __ main __。TCar对象位于0x0245C1B0>] ,但是我希望它打印列表的实际内容。

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)

我的代码有什么问题?

推荐答案

您必须定义 __ str __ 方法 __ repr __ 方法:

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)

简而言之,

__ repr __ 用于需要显示对象的原始内容的情况您会在显示列表的内容时看到,因此,如果您有汽车列表,则外观如下:

[< Car Tesla Model S 500bhp $ 100000> ;, <汽车智能Fortwo 80bhp $ 5000>]

__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 __ 如果您尝试打印实际对象,例如 print(TeslaCar),其中 TeslaCar TCar 实例。它会给您类似 Tesla Model S

__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".

这篇关于用于循环打印类的内存位置而不是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆