mirror of
https://github.com/rasbt/python_reference.git
synced 2024-11-27 22:11:13 +00:00
class search order
This commit is contained in:
parent
d85e1393fd
commit
6180a4ff75
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"name": "",
|
"name": "",
|
||||||
"signature": "sha256:e20426bb66111696c7ec4f8d754946061e129b3e332a6cc2fd00331b9540d8c5"
|
"signature": "sha256:a6418912c66fa2e2c0c8b76a1ba6cb0cb8d33c37c8fd64338d77898af4589286"
|
||||||
},
|
},
|
||||||
"nbformat": 3,
|
"nbformat": 3,
|
||||||
"nbformat_minor": 0,
|
"nbformat_minor": 0,
|
||||||
|
@ -117,6 +117,60 @@
|
||||||
],
|
],
|
||||||
"prompt_number": 2
|
"prompt_number": 2
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"So what actually happened above was that class `C` was looking in the parent class `A` for the method `.foo()` first (and found it)!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"I received an email with a nice suggestion using a more nested example to illustrate Guido van Rossum's point a little bit better:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"collapsed": false,
|
||||||
|
"input": [
|
||||||
|
"class A(object):\n",
|
||||||
|
" def foo(self):\n",
|
||||||
|
" print(\"class A\")\n",
|
||||||
|
"\n",
|
||||||
|
"class B(A):\n",
|
||||||
|
" pass\n",
|
||||||
|
"\n",
|
||||||
|
"class C(A):\n",
|
||||||
|
" def foo(self):\n",
|
||||||
|
" print(\"class C\")\n",
|
||||||
|
"\n",
|
||||||
|
"class D(B,C):\n",
|
||||||
|
" pass\n",
|
||||||
|
"\n",
|
||||||
|
"D().foo()"
|
||||||
|
],
|
||||||
|
"language": "python",
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"output_type": "stream",
|
||||||
|
"stream": "stdout",
|
||||||
|
"text": [
|
||||||
|
"class C\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"prompt_number": 3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Here, class `D` searches in `B` first, which in turn inherits from `A` (note that class `C` also inherits from `A`, but has its own `.foo()` method) so that we come up with the search order: `D, B, A, C`"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
|
|
Loading…
Reference in New Issue
Block a user