self.arg = arg和self .__ dict __ ['arg'] = arg在Python中的区别

罗德里戈·普林西比

当我定义课程时,我总是去

Class A(object):
    def __init__(self, arg):
        self.arg = arg
    def print_arg(self):
        print(self.arg)

a = A('hello')

打印a.arg

'你好'

但是我在https://github.com/pylons/webob/blob/master/src/webob/request.py的第133和134行中找到的内容让我想到了在A类中所做的与以下操作之间的区别是什么:

Class B(object):
    def __init__(self, arg):
        self.__dict__['arg'] = arg
    def print_arg(self):
            print(self.arg)

b = B(再见)

打印b.arg

'再见'

埃利·科维戈(Eli Korvigo)

有几个主要含义:

  1. 使用self.__dict__添加属性规避__setattr__,这可能与某种行为,你可能希望避免在一些地方被重载。

    In [15]: class Test(object):
        ...:     def __init__(self, a, b):
        ...:         self.a = a
        ...:         self.__dict__['b'] = b
        ...:     def __setattr__(self, name, value):
        ...:         print('Setting attribute "{}" to {}'.format(name, value))
        ...:         super(Test, self).__setattr__(name, value)
        ...:               
    
    In [16]: t = Test(1, 2)
    Setting attribute "a" to 1
    

    您可以看到没有为attribute打印任何内容b

  2. 在某些情况下不太灵活

    In [9]: class WithSlots(object):
       ...:     __slots__ = ('a',)
       ...:     def __init__(self, a):
       ...:         self.__dict__['a'] = a
       ...:         
    
    In [10]: instance = WithSlots(1)
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-10-c717fcc835a7> in <module>()
    ----> 1 instance = WithSlots(1)
    
    <ipython-input-9-2d23b670e0fc> in __init__(self, a)
          2     __slots__ = ('a',)
          3     def __init__(self, a):
    ----> 4         self.__dict__['a'] = a
          5 
    
    AttributeError: 'WithSlots' object has no attribute '__dict__'
    
    In [11]: class WithSlots(object):
        ...:     __slots__ = ('a',)
        ...:     def __init__(self, a):
        ...:         self.a = a
        ...:         
        ...:         
    
    In [12]: instance = WithSlots(1) # -> works fine
    
  3. 您不能在类定义之外执行此操作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章