python之函数用法__setattr__

本文通过一个具体的Python类实例,展示了如何使用__setattr__方法来自定义属性赋值行为。通过重写__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'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值