本文實例講述了Python面向對象之類和對象屬性的增刪改查操作。分享給大家供大家參考,具體如下:
一、類屬性的操作
# -*- coding:utf-8 -*-#! python2class 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.dangdel Chinese.countryprint(Chinese.__dict__)運行結果:
China
Japan
{'name': 'alex'}
Japan
武林站長站
武林站長站
{'__module__': '__main__', 'play_ball': <function play_ball at 0x01AAB7B0>, '__doc__': None, '__init__': <function __init__ at 0x01AAB830>}
二、對象屬性的操作
# -*- coding:utf-8 -*-#! python2class 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 = 18print(p1.__dict__)print(p1.age)p1.test = test #將外界的方法作為函數屬性加入類中print(p1.__dict__)p1.test()#修改屬性p1.age = 19print(p1.__dict__)print(p1.age)#刪除屬性del p1.ageprint(p1.__dict__)運行結果:
{'name': 'alex'}
alex
<bound method Chinese.play_ball of <__main__.Chinese instance at 0x01AE9DA0>>
{'age': 18, 'name': 'alex'}
18
{'test': <function test at 0x01AEB7F0>, 'age': 18, 'name': 'alex'}
對象方法的屬性
{'test': <function test at 0x01AEB7F0>, 'age': 19, 'name': 'alex'}
19
{'test': <function test at 0x01AEB7F0>, 'name': 'alex'}
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答