-3

From my understanding, the function super should allow a Class that is nested within another to access its parent's 'self'. I may be wrong on this, but here is a simple example of what I'm trying to achieve:

class Test:
     def __init__(self):
         self.message = "Hello World"
     class Print:
         def __init__(self):
             print super(Test, self).message


this = Test()
this.Print()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home1/users/joe.borg/<ipython-input-3-3eb5db70be43> in <module>()
----> 1 this.Print()

/home1/users/joe.borg/<ipython-input-1-cee67a2914c3> in __init__(self)
      4     class Print:
      5         def __init__(self):
----> 6             print super(Test, self).message
      7 

TypeError: must be type, not classobj
joedborg
  • 17,651
  • 32
  • 84
  • 118
  • 2
    Why do you think you want to nest classes like that? – Wooble Feb 16 '12 at 12:39
  • 4
    Your understanding of `super()` is simply wrong, you may want to start from the [official doc](http://docs.python.org/library/functions.html#super). Even thouhg `super()` might be tricky, it's a topic well covered arount the internet. – Rik Poggi Feb 16 '12 at 12:40
  • To me, there is a lot of interest in nesting classes. Just an example http://stackoverflow.com/questions/78799/is-there-a-benefit-to-defining-a-class-inside-another-class-in-python – joedborg Feb 16 '12 at 15:10

3 Answers3

5

super is supposed to be used to call the next method in the mro (method resolution order) of a given class (which is usually the method from the parent class). That's something completely different to what you're trying to do.

In addition to this, your classes are old-style classes (they don't subclass object), so super complains because it only works with new-style classes.

jcollado
  • 39,419
  • 8
  • 102
  • 133
4

The error you get spurs from the fact that super only works with new-style classes, i.e. classes that explicitly extend object.

Besides, super allows you to delegate method calls to a parent or sibling class in a linearized inheritance tree. However, nested classes are not bound by an inheritance relationship; so, even if you fixed the error (i.e. allowing Test and Print to extend object), super would not work in this case.

Giulio Piancastelli
  • 15,368
  • 5
  • 42
  • 62
0

I've got the desired results like this:

class Test(object):
     def __init__(self):
         self.message = "Hello World"
class Print(Test):
         def __init__(self):
             print super(Print, self).message
joedborg
  • 17,651
  • 32
  • 84
  • 118