mirror of
https://github.com/github/codeql.git
synced 2025-12-24 20:56:33 +01:00
35 lines
1.3 KiB
XML
35 lines
1.3 KiB
XML
<!DOCTYPE qhelp PUBLIC
|
|
"-//Semmle//qhelp//EN"
|
|
"qhelp.dtd">
|
|
<qhelp>
|
|
<overview>
|
|
<p>Special methods (sometimes also called magic methods) are how user defined classes interact with the Python virtual machine.
|
|
For example, for a class to support addition it must implement the <code>__add__</code> and <code>__radd__</code> special methods.
|
|
When the expression <code>a + b</code> is evaluated the Python virtual machine will call <code>type(a).__add__(a, b)</code> and if that
|
|
is not implemented it will call <code>type(b).__radd__(b, a)</code>.</p>
|
|
<p>
|
|
Since these special methods are always called by the virtual machine with a fixed number of parameters, if the method is implemented with
|
|
a different number of parameters it will fail at runtime with a <code>TypeError</code>.
|
|
</p>
|
|
|
|
</overview>
|
|
<recommendation>
|
|
<p>Ensure that the method has the correct number of parameters</p>
|
|
|
|
</recommendation>
|
|
<example>
|
|
<p>In the example the <code>__str__</code> method has an extra parameter. This means that if <code>str(p)</code> is called when <code>p</code>
|
|
is a <code>Point</code> then it will fail with a <code>TypeError</code>.
|
|
</p>
|
|
|
|
<sample src="SignatureSpecialMethods.py" />
|
|
|
|
</example>
|
|
<references>
|
|
|
|
<li>Python Language Reference: <a href="http://docs.python.org/dev/reference/datamodel.html#special-method-names">Special Method Names</a>.</li>
|
|
|
|
|
|
</references>
|
|
</qhelp>
|