Python面向?qū)ο笾惡蛯?duì)象屬性的增刪改查操作示例
本文實(shí)例講述了Python面向?qū)ο笾惡蛯?duì)象屬性的增刪改查操作。分享給大家供大家參考,具體如下:
一、類屬性的操作
# -*- coding:utf-8 -*- #! python2 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__)
運(yùn)行結(jié)果:
China
Japan
{'name': 'alex'}
Japan
腳本之家
腳本之家
{'__module__': '__main__', 'play_ball': <function play_ball at 0x01AAB7B0>, '__doc__': None, '__init__': <function __init__ at 0x01AAB830>}
二、對(duì)象屬性的操作
# -*- coding:utf-8 -*- #! python2 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("對(duì)象方法的屬性") 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 #將外界的方法作為函數(shù)屬性加入類中 print(p1.__dict__) p1.test() #修改屬性 p1.age = 19 print(p1.__dict__) print(p1.age) #刪除屬性 del p1.age print(p1.__dict__)
運(yùn)行結(jié)果:
{'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'}
對(duì)象方法的屬性
{'test': <function test at 0x01AEB7F0>, 'age': 19, 'name': 'alex'}
19
{'test': <function test at 0x01AEB7F0>, 'name': 'alex'}
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
對(duì)numpy中的transpose和swapaxes函數(shù)詳解
今天小編就為大家分享一篇對(duì)numpy中的transpose和swapaxes函數(shù)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08TensorFlow卷積神經(jīng)網(wǎng)絡(luò)MNIST數(shù)據(jù)集實(shí)現(xiàn)示例
這篇文章主要介紹了TensorFlow卷積神經(jīng)網(wǎng)絡(luò)MNIST數(shù)據(jù)集的實(shí)現(xiàn)示例的過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-11-11python使用pycharm環(huán)境調(diào)用opencv庫
這篇文章主要介紹了python使用pycharm環(huán)境調(diào)用opencv庫,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-02-02python中l(wèi)ambda與def用法對(duì)比實(shí)例分析
這篇文章主要介紹了python中l(wèi)ambda與def用法對(duì)比,實(shí)例分析了lambda與def的區(qū)別與使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-04-04python中報(bào)錯(cuò)"json.decoder.JSONDecodeError: Expecting value:"的解決
這篇文章主要介紹了python中報(bào)錯(cuò)"json.decoder.JSONDecodeError: Expecting value:"的解決方法 ,需要的朋友可以參考下2019-04-04