python之函数用法__setattr__
生活随笔
收集整理的這篇文章主要介紹了
python之函数用法__setattr__
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函數用法__setattr__ #http://www.cnblogs.com/hongfei/p/3858256.html
#用__setattr__函數重構方法 class Fruit(): def __init__(self,color,price): self.__color = color self.__price = price def __setattr__(self,name,value):#重構方法__setattr__方法,沒有該方法會默認存在該方法 self.__dict__[name] = str('xiaodeng,')+str(value) #為了看出區別,特意在__setattr__方法中加了str('xiaodeng') if __name__ == "__main__": fruit = Fruit("blue", 10) print fruit #__main__.Fruit instance print fruit.__dict__ #{'_Fruit__price': 'xiaodeng,10', '_Fruit__color': 'xiaodeng,blue'} print fruit.__dict__.get("_Fruit__price") #xiaodeng,10 #給_Fruit__price設置新的屬性 fruit.__dict__["_Fruit__color"] = 'red' print fruit.__dict__.get("_Fruit__color") #red #增加新的屬性和屬性值 fruit.__dict__['name']='xiaodeng' print fruit.__dict__ #{'_Fruit__price': 'xiaodeng,10', 'name': 'xiaodeng', '_Fruit__color': 'red'}
總結
以上是生活随笔為你收集整理的python之函数用法__setattr__的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hibernate工作原理(1)
- 下一篇: 使用UtraISO为U盘制作系统启动盘