Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Superclass attribute shadows subclass method

ID: py/attribute-shadows-methodKind: problemSecurity severity: Severity: errorPrecision: highTags:   - quality   - reliability   - correctnessQuery suites:   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

When an object has an attribute that shares its name with a method on the object’s class (or another class attribute), the instance attribute is prioritized during attribute lookup, shadowing the method. If a method on a subclass is shadowed by an attribute on a superclass in this way, this may lead to unexpected results or errors, as this shadowing behavior is nonlocal and may be unintended.

Recommendation

Ensure method names on subclasses don’t conflict with attribute names on superclasses, and rename one. If the shadowing behavior is intended, ensure this is explicit in the superclass.

Example

In the following example, the_foo attribute of classA shadows the method_foo of classB. Calls toB()._foo() will result in aTypeError, as3 will be called instead.

classA:def__init__(self):self._foo=3classB(A):# BAD: _foo is shadowed by attribute A._foodef_foo(self):return2

In the following example, the behavior of thedefault attribute being shadowed to allow for customization during initialization is intended in within the superclassA. Overridingdefault in the subclassB is then OK.

classA:def__init__(self,default_func=None):ifdefault_funcisnotNone:self.default=default_func# GOOD: The shadowing behavior is explicitly intended in the superclass.defdefault(self):return[]classB(A):# Subclasses may override the method `default`, which will still be shadowed by the attribute `default` if it is set.# As this is part of the expected behavior of the superclass, this is fine.defdefault(self):return{}

[8]ページ先頭

©2009-2025 Movatter.jp