__init__ 和 __str__
阿新 • • 發佈:2018-04-19
urn 顯示 。。 nbsp rod div clas spa code
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) ~
__init__ 和 __str__