2.23python str方法

#定义__str()__方法 定义对象打印的方法,将对象转化为字符串
#在python中方法名如果是__xxxx__()的,那么就算特殊的功能,因此叫做‘魔法’方法
#当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
"""class Car:
def __init__(self,wheelnum,newcolor):
self.wheelnum = wheelnum
self.color = newcolor
def __str__(self):
msg = "嘿..我的颜色是"+self.color +'我有'+str(self.wheelnum)+'个轮胎'
return msg
def move(self):
print('车在跑,目标在:夏威夷')

当调用Car这个类
"""
class Car:
    def __init__(self, wheelnum, newcolor):
        self.wheelnum = wheelnum
        self.color = newcolor

    def __str__(self):
        msg = "嘿..我的颜色是" + self.color + '我有' + str(self.wheelnum) + '个轮胎'
        return msg


c = Car(45,'黑色')
print(c)
#报错:can only concatenate str (not "int") to str   注意msg中的str(self.wheelnum)
#务必要使用str将原本输入的数字转化为字符串,否则报错
 
posted @ 2020-05-17 21:27  yescarf  阅读(144)  评论(0编辑  收藏  举报