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

thomas.lynch at reasoningtechnology.com thomas.lynch at reasoningtechnology.com
Wed Aug 15 16:00:08 EDT 2018


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)

def f_ut_oh():
   a = A()
   flag1 = a.number == 1
   a.biginc()
   flag2 = a.number == 108

   b = B()
   flag3 = b.number == 1
   b.biginc() 
   flag4 = b.number == 215

   if flag1 and flag2 and flag3 and flag4 :
     print("all good!") # this prints for me when I run this in 3.6
   else:
     print("hmm something went wrong..")

print("loaded try_adding_method_decorator.py")

Python 3.6.6 (default, Jun 27 2018, 14:44:17) 
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> python.el: native completion setup loaded
>>> loaded try_adding_method_decorator.py
>>> f_ut_oh()
making a B
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/rt-fra/src/server-side/try_adding_method_decorator.py", line 34, in f_ut_oh
    b.biginc() 
  File "/home/rt-fra/src/server-side/try_adding_method_decorator.py", line 19, in B_biginc
    super().biginc() # super() trips up
RuntimeError: super(): __class__ cell not found
>>> 

<--------------------------------

It appears that supper() doesn't work with externally defined methods, but surely that can't be.  What is the incantation that makes this work?? Thanks!

(using setattr had the same results,  AA.biginc() said AA wasn't defined .. being a class instead of an object I guess.  Putting in another self.super() didn't work ..)



More information about the Python-list mailing list