0

just a very simple thing, is there a way to access outer class from the inner class definition, like this:

class Model:
  class Options:
    model = Model   <-- error!

I nest Options inside Model because semantically these Options exist only in the scope of model, so it seems appropriate.

Thanks, Alex

4
  • 4
    Why would you want to store the (outer) class in a (inner) class variable? Commented Jul 27, 2011 at 20:17
  • I think this is more of a design implementation flaw than a language problem. Commented Jul 27, 2011 at 20:19
  • I don't have to store it in a variable, but I'd like to use the outer class in the inner class, since they are semantically related. Variable is just an example... Commented Jul 27, 2011 at 20:23
  • You can, but not at class level (as that's evaluate at class definition time, while methods usually don't get called before the class definitions finish running). Commented Jul 27, 2011 at 20:29

4 Answers 4

2

I am not sure this is exactly what you wanted but try:

class Model:
    class Option:
        @property
        def model(self): return Model
Sign up to request clarification or add additional context in comments.

Comments

1

Well, you can at least instantiate the outer class in a method of the inner class:

class Model:
    class Options:
        def __init__(self):
            model = Model()

2 Comments

but then if you instantiate Options in Model.__init__ you'll recurse.
just do model = Model instead of model = Model()
1

Try:

class Model:
    pass

class Options:
    model = Model

Comments

0

Another solution is to do the assignment after the class definition.

class Model:
  class Options:
    pass

Model.Options.model = Model

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.