【发布时间】:2019-01-09 04:35:54
【问题描述】:
class Car:
def __init__(self, mileage, make, model):
self.mileage = mileage
self.make = make
self.model = model
def printCar(self):
return "The Model is:" + self.model + " the make is: " + self.make + " and the mileage is: " + self.mileage
car = Car(100, 'Suzuki', 'Brezza')
print(car.printCar())
看到的错误: return "The Model is:" + self.model + " the make is: " + self.make + " and the mileage is: " + self.mileage TypeError: 必须是 str,而不是 int
请帮忙,我是python的初学者...
【问题讨论】:
-
100 不是字符串,是整数。
-
如果我想传递一个整数作为参数怎么办
-
另请注意,像这样的重复连接效率很低,因为它必须为 each 连接的结果创建一个临时字符串。对于这样的场景,您可以避免该成本并且避免需要担心使用格式字符串的类型(格式字符串的默认行为已经对输入进行字符串化),将您的代码更改为
return "The Model is:{} the make is: {} and the mileage is: {}".format(self.model, self.make, self.mileage)(或带有 f 字符串的 Python 3.6,return f"The Model is:{self.model} the make is: {self.make} and the mileage is: {self.mileage}")。 -
@Bazingaa:您可能不想将
mileage属性永久更改为str;里程自然是数字,您希望能够以数字方式使用它(驾驶汽车 10 英里,用self.mileage += 10反映它)。转换为str仅用于生成格式化输出。 -
附加说明:通常情况下,您不会像这样创建
printCar方法;您只需定义__str__特殊方法(与printCar相同的原型,只需将名称更改为__str__),这将允许无缝转换为字符串(您可以只做print(car),而不是print(car.printCar())) .
标签: python python-3.x python-2.7