【问题标题】:Why does the below code throw typeError? [duplicate]为什么下面的代码会抛出 typeError? [复制]
【发布时间】: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


【解决方案1】:
def printCar(self):
    return "The Model is:" + self.model + " the make is: " + self.make + " and the mileage is: " + str(self.mileage)

注意将int 转换为stringstr 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多