Python 用于循环打印类而不是列表的内存位置
我有一些代码似乎要打印Python 用于循环打印类而不是列表的内存位置,python,class,python-3.x,for-loop,Python,Class,Python 3.x,For Loop,我有一些代码似乎要打印[],但我希望它打印列表的实际内容 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(
[]
,但我希望它打印列表的实际内容
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)
我的代码有什么问题?您必须为此定义一个或一个方法:
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)
class TCar():
定义初始值(自身、品牌、型号、发动机规格、价格):
self.Make=str(Make)
self.Model=str(Model)
self.EngineSize=浮动(EngineSize)
self.Price=浮动(价格)
定义报告(自我):
返回“”。格式(self.Make、self.Model、self.EngineSize、self.Price)
定义(自我):
返回“{0}{1}”。格式(self.Make,self.Model)
简言之
\uuuu repr\uuuuu
用于需要显示对象的“原始”内容的情况,它是您在显示列表内容时看到的类型,因此如果您有一个汽车列表,它将如下所示:[,]
如果您试图打印实际对象,如
print(TeslaCar)
而TeslaCar
是TCar
实例,则使用\uu str\uuuuuuu
。它会给你一些类似于“特斯拉S型”的东西你这里有一个对象列表。添加如下内容:-
def __str__(self):
print self.Make, self.Model, self.EngineSize, self.Price
这将打印对象所有属性的值。或者,您可以根据您的行为要求修改函数。您可以覆盖
\uuuu str\uuu
或\uu repr\uu
,如下所示:
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$)]
另外,您可能希望查看关于
\uuuu str\uuuu
与\uuu repr\uuuu
逐个打印属性,而不是一次性打印garange:print(self.attribute)。请注意,代码中的属性是对象的实例您需要定义一个def\uu str\uuuuuu(self):
您还将在列表中看到repr输出