旧式类中的 __slots__
¶
ID: py/slots-in-old-style-class
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- portability
- correctness
Query suites:
- python-security-and-quality.qls
仅新式类支持使用 __slots__
声明覆盖类字典的功能。当您将 __slots__
声明添加到旧式类时,它只会创建一个名为 __slots__
的类属性。
建议¶
如果您想覆盖类的字典,那么请确保该类是新式类。您可以通过从 object
继承来将旧式类转换为新式类。
示例¶
在以下 Python 2 示例中,Point
类是旧式类(没有继承)。此类中的 __slots__
声明创建了一个名为 __slots__
的类属性,类字典不受影响。 Point2
类是新式类,因此 __slots__
声明会为 slots 列表中的每个名称创建特殊的紧凑属性,并且通过不创建属性字典来节省空间。
class Point:
__slots__ = [ '_x', '_y' ] # Incorrect: 'Point' is an old-style class.
# No slots are created.
# Instances of Point have an attribute dictionary.
def __init__(self, x, y):
self._x = x
self._y = y
class Point2(object):
__slots__ = [ '_x', '_y' ] # Correct: 'Point2' is an new-style class
# Two slots '_x' and '_y' are created.
# Instances of Point2 have no attribute dictionary.
def __init__(self, x, y):
self._x = x
self._y = y