Home  >  Q&A  >  body text

python - object.__setattr__和直接设置属性有什么不同吗?

在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__ = {}的话是否效果一样呢?

迷茫迷茫2712 days ago573

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 10:22:12

    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)

    reply
    0
  • Cancelreply