|
3 | 3 | "qhelp.dtd"> |
4 | 4 | <qhelp> |
5 | 5 | <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. |
10 | 12 | </p> |
11 | 13 |
|
12 | 14 | </overview> |
13 | 15 | <recommendation> |
14 | 16 |
|
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> |
16 | 21 |
|
17 | 22 | </recommendation> |
18 | 23 | <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> |
23 | 34 |
|
24 | | -<sample src="SubclassShadowing.py" /> |
25 | 35 |
|
26 | 36 | </example> |
27 | 37 | </qhelp> |
0 commit comments