【发布时间】:2017-06-13 02:14:30
【问题描述】:
我阅读了usage of slots 上的主要答案,它让我了解了如何以及在何处使用__slots__。
现在,我将代码从 Python 2 移植到 Python 3,类似于以下内容:
class B(object):
__slots__ = ('_fields')
_fields = set()
但这会在 Python 2 上正常工作时给出错误 Python 3:
ValueError: '_fields' in __slots__ conflicts with class variable.
我把代码改成
class B(object):
__slots__ = ('_fields')
def __init__(self):
_fields = set()
而且效果很好。我的问题是,它甚至是正确的变化吗?
正如我从原始代码中得到的那样,我想这是说不要使用 __dict__ 来节省内存或加快访问速度或其他任何原因,但同时也试图将属性类型指定为 _field 为放()。上面的改变是正确的表达方式还是会产生一些副作用。
进一步的实验: 我进一步试验了以下变体(在 Python 3 上):
import pdb
class A(object):
a = set()
'''
class B(object):
__slots__ = ('a')
a = set()
'''
class C(object):
__slots__ = ('a')
def __init__(self):
a = set()
class D(object):
def __init__(self):
__slots__ = ('a')
a = set()
if __name__ == '__main__':
#pdb.set_trace()
x = A(); print(dir(x))
#y = B()
z = C(); print(dir(z))
z1 = D(); print(dir(z1))
它给出了以下输出。
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'a']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
我们可以看到只有 C 对象显示正确的足迹,即没有 __dict__ 并且只有 __slots__ 。这不是我们想要的理想吗?对__weakref__ 的任何解释也会有所帮助。
同样在 Python 2 上,B 和 C 对象都显示相同的足迹。基于此,C 应该是正确的表达方式,因为它也在 Python 2 和 3 上编译。
【问题讨论】:
标签: python initialization slots