python3 之__str__

当某个类定义了__str__方法是,打印该类的实例对象就是打印__str__方法return出来的数据
示例:
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

猜你喜欢

转载自www.cnblogs.com/raind/p/9478172.html