mirror of
https://github.com/github/codeql.git
synced 2025-12-16 16:53:25 +01:00
Update documentation
This commit is contained in:
@@ -1,17 +1,9 @@
|
||||
class Mammal(object):
|
||||
|
||||
def __init__(self, milk = 0):
|
||||
self.milk = milk
|
||||
|
||||
|
||||
class Cow(Mammal):
|
||||
|
||||
class A:
|
||||
def __init__(self):
|
||||
Mammal.__init__(self)
|
||||
self._foo = 3
|
||||
|
||||
def milk(self):
|
||||
return "Milk"
|
||||
|
||||
#Cow().milk() will raise an error as Cow().milk is the 'milk' attribute
|
||||
#set in Mammal.__init__, not the 'milk' method defined on Cow.
|
||||
class B:
|
||||
# BAD: _foo is shadowed by attribute A._foo
|
||||
def _foo(self):
|
||||
return 2
|
||||
|
||||
|
||||
@@ -3,25 +3,35 @@
|
||||
"qhelp.dtd">
|
||||
<qhelp>
|
||||
<overview>
|
||||
<p> Subclass shadowing occurs when an instance attribute of a superclass has the
|
||||
the same name as a method of a subclass, or vice-versa.
|
||||
The semantics of Python attribute look-up mean that the instance attribute of
|
||||
the superclass hides the method in the subclass.
|
||||
<p>
|
||||
When an object has an attribute that shares the same name 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.
|
||||
</p>
|
||||
|
||||
</overview>
|
||||
<recommendation>
|
||||
|
||||
<p>Rename the method in the subclass or rename the attribute in the superclass.</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
|
||||
</recommendation>
|
||||
<example>
|
||||
<p>The following code includes an example of subclass shadowing. When you call <code>Cow().milk()</code>
|
||||
an error is raised because <code>Cow().milk</code> is interpreted as the 'milk' attribute set in
|
||||
<code>Mammal.__init__</code>, not the 'milk' method defined within <code>Cow</code>. This can be fixed
|
||||
by changing the name of either the 'milk' attribute or the 'milk' method.</p>
|
||||
<p>
|
||||
In the following example, the <code>_foo</code> attribute of class <code>A</code> shadows the method <code>_foo</code> of class <code>B</code>.
|
||||
Calls to <code>B()._foo()</code> will result in a <code>TypeError</code>, as <code>3</code> will be called instead.
|
||||
</p>
|
||||
|
||||
<sample src="examples/SubclassShadowing.py" />
|
||||
|
||||
<p>
|
||||
In the following example...
|
||||
</p>
|
||||
|
||||
<sample src="SubclassShadowing.py" />
|
||||
|
||||
</example>
|
||||
</qhelp>
|
||||
|
||||
Reference in New Issue
Block a user