Alex Kreimer
Alex Kreimer

Reputation: 1106

Is there a way to access outer class in the nested class in python?

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

Upvotes: 0

Views: 259

Answers (4)

kindall
kindall

Reputation: 184151

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

class Model:
  class Options:
    pass

Model.Options.model = Model

Upvotes: 0

warvariuc
warvariuc

Reputation: 59594

Try:

class Model:
    pass

class Options:
    model = Model

Upvotes: 1

Tom Pohl
Tom Pohl

Reputation: 3094

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()

Upvotes: 1

Hgeg
Hgeg

Reputation: 545

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

class Model:
    class Option:
        @property
        def model(self): return Model

Upvotes: 2

Related Questions