tags:

views:

225

answers:

2

I have a situation like so...

class Outer(object):

    def some_method(self):
        # do something

    class Inner(object):
        def __init__(self):
            self.Outer.some_method()    # <-- this is the line in question

How can I access the Outer class's method from the Inner class?

Edit -- Thanks for the responses. I'm concluding that I need to re-assess how I had designed this to be implemented and come up with a more robust method.

+3  A: 

The methods of a nested class cannot directly access the instance attributes of the outer class.

Note that it is not necessarily the case that an instance of the outer class exists even when you have created an instance of the inner class.

In fact, it is often recommended against using nested classes, since the nesting does not imply any particular relationship between the inner and outer classes.

Daniel Vassallo
+2  A: 

Do you mean to use inheritance, rather than nesting classes like this? What you're doing doesn't make a heap of sense in Python.

You can access the Outer's some_method by just referencing Outer.some_method within the inner class's methods, but it's not going to work as you expect it will. For example, if you try this:

class Outer(object):

    def some_method(self):
        # do something

    class Inner(object):
        def __init__(self):
            Outer.some_method()

...you'll get a TypeError when initialising an Inner object, because Outer.some_method expects to receive an Outer instance as its first argument. (In the example above, you're basically trying to call some_method as a class method of Outer.)

zenbot
The reason why it probably doesn't make sense is because I'm being intentionally hacky. Adding custom methods to a QuerySet in Django requires a bit of boilerplate code, and I was attempting to derive a clever way to do it using python that allowed me to template the boilerplate code and simply write the pertinent parts in my Model code.
T. Stone
Apologies -- I don't know Django and so can't suggest a way to template the boilerplate code, but you may be barking up the wrong tree in trying to nest your classes. Your Inner class doesn't acquire anything from your Outer class. All nesting it within Outer does is force you to access it via Outer.Inner, rather than just plain Inner.
zenbot