美文网首页
python中的__str__函数作用

python中的__str__函数作用

作者: 公子小白123 | 来源:发表于2020-11-15 08:39 被阅读0次

__str__方法:总结

在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法,当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据

例子1:如:

class Car:

    def __init__(self, newWheelNum, newColor):

        self.wheelNum = newWheelNum

        self.color = newColor

    def __str__(self):

        msg = "嘿。。。我的颜色是" + self.color + "我有" + int(self.wheelNum) + "个轮胎..."

        return msg

    def move(self):

        print('车在跑,目标:夏威夷')

BMW = Car(4, "白色")

print(BMW)

例子2:如:

class Cat:

    """定义了一个Cat类"""

    #初始化对象

    def __init__(self, new_name, new_age):

        self.name = new_name

        self.age = new_age

    def __str__(self):

        return "%s的年龄是:%d"%(self.name, self.age)

    #方法

    def eat(self):

        print("猫在吃鱼....")

    def drink(self):

        print("猫正在喝kele.....")

    def introduce(self):

        print("%s的年龄是:%d"%(self.name, self.age))

#创建一个对象

tom = Cat("汤姆", 40)

lanmao = Cat("蓝猫", 10)

print(tom)

print(lanmao)

运行结果:

汤姆的年龄是:40

蓝猫的年龄是:10

相关文章

网友评论

      本文标题:python中的__str__函数作用

      本文链接:https://www.haomeiwen.com/subject/xdsvbktx.html