开发者

How to access static members of outer class from an inner class constructor?

开发者 https://www.devze.com 2023-01-31 20:22 出处:网络
How to get this to work: class ABC(object): C1 = 1 class DEF(object): def __init__(self, v=ABC.C1): self.v = v

How to get this to work:

class ABC(object):
    C1 = 1

    class DEF(object):
        def __init__(self, v=ABC.C1):
            self.v = v


a = ABC()

From the inne开发者_Go百科r class DEF, I cannot access the constant "C1". I tried with "ABC.C1" and "C1" alone but to no avail.

Please advise.


I advice you to not nest classes. Why do you do that? There is no reason to do that, ever. This works:

>>> class ABC(object):
...     C1 = 1
...  
>>> class DEF(object):
...     def __init__(self, v=ABC.C1):
...         self.v = v
...  
>>> a = ABC()
>>> d = DEF()
>>> d.v
1

The reason your code doesn't work is that ABC doesn't exist yet, as it's not been constructed. You can't access the ABC class from within it's own construction, it's not created until the end.

0

精彩评论

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