当我做一个课程定义时,我总是去
Class A(object):
def __init__(self, arg):
self.arg = arg
def print_arg(self):
print(self.arg)
Run Code Online (Sandbox Code Playgroud)
a = A('你好')
打印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)
Run Code Online (Sandbox Code Playgroud)
b = B('再见')
打印b.arg
'再见'
有几个主要含义:
使用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
Run Code Online (Sandbox Code Playgroud)
您可以看到没有为属性打印任何内容b.
在某些情况下,它不太灵活
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
Run Code Online (Sandbox Code Playgroud)你不能在类定义之外做到这一点.