Python.面向物件---類和物件屬性的增刪改查
阿新 • • 發佈:2019-01-05
一,類屬性的操作
class Chinese: country = 'China' def __init__(self,name): self.name = name def play_ball(self,ball): print('%s play %s' %(self.name,ball)) #檢視屬性 print(Chinese.country) #修改屬性 Chinese.country = 'Japan' print(Chinese.country) p1 = Chinese('alex') print(p1.__dict__) print(p1.country) #增加屬性 Chinese.dang = '共產黨' print(Chinese.dang) print(p1.dang) #刪除屬性 del Chinese.dang del Chinese.country print(Chinese.__dict__)
二,物件屬性的操作
class Chinese: country = 'China' def __init__(self,name): self.name = name def play_ball(self,ball): print('%s play %s' %(self.name,ball)) def test(): print("物件方法的屬性") p1 = Chinese('alex') print(p1.__dict__) #檢視屬性 print(p1.name) print(p1.play_ball) #增加屬性 p1.age = 18 print(p1.__dict__) print(p1.age) p1.test = test #將外界的方法作為函式屬性加入類中 print(p1.__dict__) p1.test() #修改屬性 p1.age = 19 print(p1.__dict__) print(p1.age) #刪除屬性 del p1.age print(p1.__dict__)