__init__ 和 __str__

  1 #定义一个类
  2 class Cat:
  3     #初始化
  4     def __init__(self,new_name,new_age):
  5         self.name = new_name
  6         self.age = new_age
  7 
  8     def __str__(self):
  9         return('%s的年龄是%d'%(self.name,self.age))
 10 
 11     #方法
 12     def eat(self):
 13         print('猫在吃鱼。。。')
 14 
 15     def drink(self):
 16         print('喝水。。')
 17     #第二种显示
 18     def introduce(self):
 19         print('%s的年龄是%d'%(self.name,self.age))
 20 
 21 #创建对象
 22 tom = Cat('汤姆',18)
 23 lanmao = Cat('蓝猫',30)
 24 
 25 print(tom)
 26 print(lanmao)
~                     

猜你喜欢

转载自www.cnblogs.com/Smalllv/p/8881580.html