You need to enable JavaScript to run this app. Python运行traveler类代码报TypeError: can only concatenate str (not "int") to str如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python运行traveler类代码报TypeError: can only concatenate str (not "int") to str如何解决

问题成因
  • 类型不匹配导致拼接报错:实例化traveler类时传入的id为整数1、age为整数20,而函数内直接用+把整数和字符串拼接,Python不允许字符串和整数直接相加,这就是触发TypeError的直接原因。
  • 方法调用逻辑错误:myfunc是定义在类外部的普通函数,不属于traveler类的成员方法,直接用t1.myfunc()调用会触发属性不存在的报错,哪怕先解决了类型拼接问题也无法正常运行。
可行修复方案

有两种常用修复方式,可按需选择:

方案1:将打印函数改为类成员方法,用f-string格式化输出(更符合面向对象写法,推荐)

class traveler:
    def __init__(t,id,name,age,gender):
        t.id = id
        t.name = name
        t.age = age
        t.gender = gender
    
    # 将打印函数移入类内部作为成员方法
    def myfunc(t):
        # f-string会自动处理不同类型数据的转字符串逻辑,无需手动转换
        print(f"Traveler ID is: {t.id}")
        print(f"Traveler name is: {t.name}")
        print(f"Traveler age is: {t.age}")
        print(f"Traveler gender is: {t.gender}")

t1 = traveler(1,"abc",20,"female")
t1.myfunc()

方案2:保留原函数定义,调整调用方式和拼接逻辑

class traveler:
    def __init__(t,id,name,age,gender):
        t.id = id
        t.name = name
        t.age = age
        t.gender = gender

def myfunc(printinfo):
    # 手动将整数属性转为字符串后再拼接
    print("Traveler ID is: " + str(printinfo.id))
    print("Traveler name is: " + printinfo.name)
    print("Traveler age is: " + str(printinfo.age))
    print("Traveler gender is: " + printinfo.gender)

t1 = traveler(1,"abc",20,"female")
# 直接将实例作为参数传入普通函数调用
myfunc(t1)

内容的提问来源于stack exchange,提问作者Shamal_Shine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 10:18:04