Noticing they both limit the things that can be called from outside.
__all__ = [
'Point',
]
class Point(object):
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
__all__
only affects starred imports - only names from __all__
will be imported after doing from mymodule import *
(if __all__
is present, of course). You can still access names not listed there:
In [4]: import mymodule
In [5]: mymodule.__all__
Out[5]: ['a']
In [6]: mymodule.b
Out[6]: 'was not in __all__'
__slots__
prevents the __dict__
attribute from being created (restricting the ability to set arbitrary attributes to instances of certain class):
In [10]: class A():
...: __slots__ = ('a',)
...:
In [11]: a = A()
In [12]: a.b = 'was not in __slots__'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-fb77d7bc2a79> in <module>()
----> 1 a.b = 'was not in __slots__'
AttributeError: 'A' object has no attribute 'b'
These are 2 different things.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.