手机
当前位置:查字典教程网 >脚本专栏 >python >Python __getattr__与__setattr__使用方法
Python __getattr__与__setattr__使用方法
摘要:比如下面的例子:classBook(object):def__setattr__(self,name,value):ifname=='val...

比如下面的例子: class Book(object):

def __setattr__(self, name, value):

if name == 'value':

object.__setattr__(self, name, value - 100)

else:

object.__setattr__(self, name, value)

def __getattr__(self, name):

try:

return object.__getattribute__(name)

except:

return name + ' is not found!'

def __str__(self):

return self.name + ' cost : ' + str(self.value)

c = Book()

c.name = 'Python'

c.value = 100

print c.name

print c.value

print c

print c.Type

上面的例子中,在赋值书的value属性时,偷偷的将value减去了100,呵。输出结果:

Python

0

Python cost : 0

Type is not found!

【Python __getattr__与__setattr__使用方法】相关文章:

Python中的yield浅析

wxPython 入门教程

Python httplib,smtplib使用方法

Python中的map、reduce和filter浅析

python三元运算符实现方法

Python random模块(获取随机数)常用方法和使用例子

python中的内置函数getattr()介绍及示例

python解析html开发库pyquery使用方法

Python 元类使用说明

Python中使用中文的方法

精品推荐
分类导航