当某个类定义了__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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-16
  • 2021-08-19
  • 2021-09-28
  • 2021-09-01
猜你喜欢
  • 2022-01-09
  • 2022-12-23
  • 2022-03-10
  • 2022-02-25
  • 2021-07-06
  • 2022-12-23
相关资源
相似解决方案