Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

__slots__ in old-style class

ID: py/slots-in-old-style-classKind: problemSecurity severity: Severity: errorPrecision: very-highTags:   - portability   - correctnessQuery suites:   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

The ability to override the class dictionary using a__slots__ declaration is supported only by new-style classes. When you add a__slots__ declaration to an old-style class it just creates a class attribute called__slots__.

Recommendation

If you want to override the dictionary for a class, then ensure that the class is a new-style class. You can convert an old-style class to a new-style class by inheriting fromobject.

Example

In the following Python 2 example thePoint class is an old-style class (no inheritance). The__slots__ declaration in this class creates a class attribute called__slots__, the class dictionary is unaffected. ThePoint2 class is a new-style class so the__slots__ declaration causes special compact attributes to be created for each name in the slots list and saves space by not creating attribute dictionaries.

classPoint:__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=xself._y=yclassPoint2(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=xself._y=y

References


[8]ページ先頭

©2009-2025 Movatter.jp