旧式类中的属性¶
ID: py/property-in-old-style-class
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- portability
- correctness
Query suites:
- python-security-and-quality.qls
属性描述符仅在 Python 2.1 中引入的新式类中受支持。属性描述符应仅在新式类中使用。
建议¶
如果要在类中定义属性,请确保该类是新式类。可以通过继承 object
将旧式类转换为新式类。
示例¶
在以下示例中,所有类都尝试为 x
设置属性。但是,只有第三和第四个类是新式类。因此,x
属性仅对 NewStyle
和 InheritNewStyle
类可用。
如果将 OldStyle
类定义为从新式类继承,那么 x
属性将对 OldStyle
和 InheritOldStyle
类都可用。
class OldStyle:
def __init__(self, x):
self._x = x
# Incorrect: 'OldStyle' is not a new-style class and '@property' is not supported
@property
def x(self):
return self._x
class InheritOldStyle(OldStyle):
def __init__(self, x):
self._x = x
# Incorrect: 'InheritOldStyle' is not a new-style class and '@property' is not supported
@property
def x(self):
return self._x
class NewStyle(object):
def __init__(self, x):
self._x = x
# Correct: 'NewStyle' is a new-style class and '@property' is supported
@property
def x(self):
return self._x
class InheritNewStyle(NewStyle):
def __init__(self, x):
self._x = x
# Correct: 'InheritNewStyle' inherits from a new-style class and '@property' is supported
@property
def x(self):
return self._x