how to make super() work with externally defined methods in inheritance???

Chris Angelico rosuav at gmail.com
Wed Aug 15 16:28:43 EDT 2018


On Thu, Aug 16, 2018 at 6:00 AM, thomas.lynch--- via Python-list
<python-list at python.org> wrote:
> Appreciate some help in how in Python a person can add some external methods to existing classes in the presence of simple one level inheritance.  Here is an example stripped down to the shiny brass tacks:
>
> class A:
>   def __init__(self):
>     self.number = 1
>
> def A_biginc(self):
>   self.number += 100
>
> A.biginc = A_biginc
> #setattr(A, 'biginc', A_biginc)
>
> class B(A):
>   def __init__(self):
>     super().__init__()
>     print("making a B")
>
> def B_biginc(self):
>   super().biginc() # super() trips up
>   super().biginc()
>   return self.number
>
> B.biginc = B_biginc
> #setattr(B, 'biginc', B_biginc)
>

The no-arg form of super() is a bit magical, and depends on being
compiled inside a class definition. You can use the regular form of
the function instead:

super(B, self)

On Thu, Aug 16, 2018 at 6:17 AM, Calvin Spealman <cspealma at redhat.com> wrote:
> You really can't, and shouldn't. The super() helper relies on information
> that exists inside the class definition and which is not available simply
> at runtime by virtue of being attached to the class.
>
> Besides, modifying classes externally is generally considered a bad idea.
> Maybe you could accomplish this with a subclass adding this method, instead.

When used correctly, it's perfectly acceptable. It's a feature for a reason.

ChrisA



More information about the Python-list mailing list