python - object.__setattr__和直接设置属性有什么不同吗?
迷茫
迷茫 2017-04-18 10:20:12
0
1
572

在werkzeug中有这样的定义:

class Local(object):
    __slots__ = ('__storage__', '__ident_func__')

    def __init__(self):
        object.__setattr__(self, '__storage__', {})
        object.__setattr__(self, '__ident_func__', get_ident)

此处的__init__方法里,使用self.__storage__ = {}的话是否效果一样呢?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
巴扎黑

The effect is actually the same.
For exampleobject.a = 1最终也是调用self.__setattr__('a', 1);
But when you override the __setattr__ method of the parent class (object), you can add some rules you define, such as:

def __setattr__(self, name, value):
    if name == 'xxx':
        print 'Hi, I can't do it.'
    else:
        super(Local, self).__setattr__(name, value)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!