-1

I'm trying to initialize an inheriting class inside another class, but it doesn't work and I don't know how to solve.

I've read here that inheriting generally works following way:

class Foo(object):
    def __init__(self, text):
        print text

class Bar(Foo):
    def __init__(self, text):
        super(Bar, self).__init__(text)

This works, however, if I put the Bar-class into another class, the code doesn't work anymore.

class Whatever(object):
    class Bar(Foo):
        def __init__(self, text):
            super(Bar, self).__init__(text)

    def __init__(self, text):
        test = self.Bar(text)

Python gets confused with the namespace:

super(Bar, self).__init__(text)
NameError: global name 'Bar' is not defined

What to do? Thanks!

Community
  • 1
  • 1
Nearoo
  • 4,454
  • 3
  • 28
  • 39
  • Try referring to `Bar` as `Whatever.Bar`. – Ankur Ankan Jun 09 '14 at 09:22
  • Tried. Works. Thank you! :) – Nearoo Jun 09 '14 at 09:23
  • This hasn't anything to do with class inheritance. If `Bar` inherited from `object`, you'd *still* get the same error. If `Bar` didn't inherit from anything, the same error would occur. That's because `Bar` is not a global when you make it an attribute of another class instead. – Martijn Pieters Jun 09 '14 at 09:35
  • @MartijnPieters You're right, I didn't think properly, a class witch is in its own nametable wouldn't make sense at all. @LennartRegebro Because the obvious reason: Every `Whatever` needs a `Foo`, but not always the exact same... – Nearoo Jun 09 '14 at 10:05
  • @user3424423: I actually missed the `super()` line; I was referring to the `test = Bar(text)` line. – Martijn Pieters Jun 09 '14 at 10:38

1 Answers1

1

Problem solved.

You have to refer to Bar with Whatever.Bar, so it looks like this:

class Whatever(object):
    class Bar(Foo):
        def __init__(self, text):
            super(Whatever.Bar, self).__init__(text)

    def __init__(self, text):
        test = self.Bar(text)
Nearoo
  • 4,454
  • 3
  • 28
  • 39
  • 1
    And you could also use `self.Bar` instead of `Whatever.Bar`. – Ankur Ankan Jun 09 '14 at 09:27
  • No, you can't. (Don't ask me why) This produces the error `'Bar' has no attribute 'Bar'` – Nearoo Jun 09 '14 at 09:55
  • Actually I know why. If you write `self.bar`, python searches for the `Bar` in the local namespace of `Bar`. If you write `Bar` only, it searches in the namespace of the `__init__()`-Method, and if it doesn't find anything, it looks in the global-Namespace. You have to write `Whatever.Bar`, because `Whatever.Bar` is in the global-Namespace, `Bar` is not. – Nearoo Jun 09 '14 at 10:12
  • @user3424423: there are *two* locations you need to adjust your `Bar` reference. The `Whatever.__init__` method also needs to qualify `Bar` (it is currently looking for a global). It is *there* you can use `self.Bar` as well as `Whatever.Bar`. – Martijn Pieters Jun 09 '14 at 10:37