python中類的學習筆記(源碼版)
阿新 • • 發佈:2018-04-14
類的使用1.1第一段代碼
#定義一個類(define a class ) class Cat: #屬性(attribution) #方法(methods) def eat(self): print("cat is eating a fish.") def drink(slef): print("cat is drinking milk.") def introduce(self): print("%s‘s age is %d"%(tom.chinese_name,tom.age)) #創建一個對象(creating an object) tom = Cat() #調用一個對象的方法(method to invoke an object) tom.eat() tom.drink() #蠢辦法添加屬性(stupid method to add attributions) tom.chinese_name = "湯姆" tom.age = 18 #獲取對象的屬性(the first way to get properties of objects ) tom.introduce() #創建多個對象,這裏創建第二個對象blue_cat(create multiple objects,and the second creates bule cat) blue_cat = Cat() blue_cat.chinese_name = "藍貓" blue_cat.age = 8 blue_cat.introduce()
1.2執行第一段代碼的輸出
[root@localhost class]# python test.py
cat is eating a fish.
cat is drinking milk.
湯姆‘s age is 18
湯姆‘s age is 18
‘‘‘
那這裏我們可以看到兩個不同的對象調用方法後輸出了相同的結果,這就出現問題了,
那怎麽解決上面的問題,且看下面的代碼。
‘‘‘
2.1第2種方式
self的加入,解決了上面的問題。
#定義一個類(define a class ) class Cat: #屬性(attribution) #方法(methods) def eat(self): print("cat is eating a fish.") def drink(slef): print("cat is drinking milk.") def introduce(self): print("%s‘s age is %d."%(self.chinese_name,self.age)) #創建一個對象(creating an object) tom = Cat() #調用一個對象的方法(method to invoke an object) tom.eat() tom.drink() #蠢辦法添加屬性(stupid method to add attributions) tom.chinese_name = "湯姆" tom.age = 18 #獲取對象的屬性(the first way to get properties of objects ) tom.introduce() #創建多個對象,這裏創建第二個對象blue_cat(create multiple objects,and the second creates bule cat) blue_cat = Cat() blue_cat.chinese_name = "藍貓" blue_cat.age = 8 blue_cat.introduce()
2.2第二段代碼的輸出
[root@localhost class]# python test.py
cat is eating a fish.
cat is drinking milk.
湯姆‘s age is 18.
藍貓‘s age is 8.
3 init和str的使用
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("貓正在喝牛奶.....") def introduce(self): print("%s的年齡是:%d"%(self.name, self.age)) #創建一個對象 tom = Cat("湯姆", 40) bule_cat = Cat("藍貓", 10) print(tom) print(bule_cat) [root@localhost class]# python test2.py 湯姆的年齡是:40 藍貓的年齡是:10
python中類的學習筆記(源碼版)