mirror of
https://github.com/python/cpython.git
synced 2025-11-08 21:52:45 +00:00
[doc] Teach 0-args form of super in Programming FAQ (GH-22176)
This commit is contained in:
parent
5c0eed7375
commit
778ad926cb
1 changed files with 7 additions and 8 deletions
|
|
@ -1504,20 +1504,19 @@ Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
|
||||||
local state for self without causing an infinite recursion.
|
local state for self without causing an infinite recursion.
|
||||||
|
|
||||||
|
|
||||||
How do I call a method defined in a base class from a derived class that overrides it?
|
How do I call a method defined in a base class from a derived class that extends it?
|
||||||
--------------------------------------------------------------------------------------
|
------------------------------------------------------------------------------------
|
||||||
|
|
||||||
Use the built-in :func:`super` function::
|
Use the built-in :func:`super` function::
|
||||||
|
|
||||||
class Derived(Base):
|
class Derived(Base):
|
||||||
def meth(self):
|
def meth(self):
|
||||||
super(Derived, self).meth()
|
super().meth() # calls Base.meth
|
||||||
|
|
||||||
For version prior to 3.0, you may be using classic classes: For a class
|
In the example, :func:`super` will automatically determine the instance from
|
||||||
definition such as ``class Derived(Base): ...`` you can call method ``meth()``
|
which it was called (the ``self`` value), look up the :term:`method resolution
|
||||||
defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
|
order` (MRO) with ``type(self).__mro__``, and return the next in line after
|
||||||
arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to
|
``Derived`` in the MRO: ``Base``.
|
||||||
provide the ``self`` argument.
|
|
||||||
|
|
||||||
|
|
||||||
How can I organize my code to make it easier to change the base class?
|
How can I organize my code to make it easier to change the base class?
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue