欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python __getattr__与__setattr__使用方法

程序员文章站 2022-09-30 12:31:37
比如下面的例子: class book(object):    def __setattr__(self, name, value):&nb...
比如下面的例子:
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!