Skip to content

Commit 34317d2

Browse files
Update documentation
1 parent 796a606 commit 34317d2

File tree

2 files changed

+26
-24
lines changed

2 files changed

+26
-24
lines changed
Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,9 @@
1-
class Mammal(object):
2-
3-
def __init__(self, milk = 0):
4-
self.milk = milk
5-
6-
7-
class Cow(Mammal):
8-
1+
class A:
92
def __init__(self):
10-
Mammal.__init__(self)
11-
12-
def milk(self):
13-
return "Milk"
3+
self._foo = 3
144

15-
#Cow().milk() will raise an error as Cow().milk is the 'milk' attribute
16-
#set in Mammal.__init__, not the 'milk' method defined on Cow.
5+
class B:
6+
# BAD: _foo is shadowed by attribute A._foo
7+
def _foo(self):
8+
return 2
179

python/ql/src/Classes/SubclassShadowing.qhelp

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,35 @@
33
"qhelp.dtd">
44
<qhelp>
55
<overview>
6-
<p> Subclass shadowing occurs when an instance attribute of a superclass has the
7-
the same name as a method of a subclass, or vice-versa.
8-
The semantics of Python attribute look-up mean that the instance attribute of
9-
the superclass hides the method in the subclass.
6+
<p>
7+
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
8+
prioritized during attribute lookup, shadowing the method.
9+
10+
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
11+
shadowing behavior is nonlocal and may be unintended.
1012
</p>
1113

1214
</overview>
1315
<recommendation>
1416

15-
<p>Rename the method in the subclass or rename the attribute in the superclass.</p>
17+
<p>
18+
Ensure method names on subclasses don't conflict with attribute names on superclasses, and rename one.
19+
If the shadowing behavior is intended, ensure this is explicit in the superclass.
20+
</p>
1621

1722
</recommendation>
1823
<example>
19-
<p>The following code includes an example of subclass shadowing. When you call <code>Cow().milk()</code>
20-
an error is raised because <code>Cow().milk</code> is interpreted as the 'milk' attribute set in
21-
<code>Mammal.__init__</code>, not the 'milk' method defined within <code>Cow</code>. This can be fixed
22-
by changing the name of either the 'milk' attribute or the 'milk' method.</p>
24+
<p>
25+
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>.
26+
Calls to <code>B()._foo()</code> will result in a <code>TypeError</code>, as <code>3</code> will be called instead.
27+
</p>
28+
29+
<sample src="examples/SubclassShadowing.py" />
30+
31+
<p>
32+
In the following example...
33+
</p>
2334

24-
<sample src="SubclassShadowing.py" />
2535

2636
</example>
2737
</qhelp>

0 commit comments

Comments
 (0)