开发者

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

开发者 https://www.devze.com 2023-03-23 03:45 出处:网络
just a very simple thing, is there a way to access outer class from the inner class definition,like this:

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


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

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


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


Try:

class Model:
    pass

class Options:
    model = Model


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

class Model:
  class Options:
    pass

Model.Options.model = Model
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号