Python __getattr__与__setattr__使用方法
时间:2020-10-27 15:37:08|栏目:Python代码|点击: 次
比如下面的例子:
0
Python cost : 0
Type is not found!
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
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,呵。输出结果:
0
Python cost : 0
Type is not found!
栏 目:Python代码
本文标题:Python __getattr__与__setattr__使用方法
本文地址:http://www.codeinn.net/misctech/16392.html