Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: nested classes: access outer class class member

This does not work:

class A:
  a1 = 4

  class B:
    b1 = A.a1  # Fails
    b2 = 6

  class C:
    c1 = A.B.b2  # Fails

Any non cryptic way to solve it? I know I could take B and C out from A but I would like to keep them embedded. I also think it would be easier with no class members as they could easily passed to nested class as argument in constructor, but being all of them class members I do not know how to do some similar thing here. I have also read on some thread that this usage remembers using classes as namespaces and that should be solved using modules, not classes, but above classes are real classes for me (I construct instances) with class data in adition that I would like to share among them.

like image 590
user2761220 Avatar asked Sep 16 '16 17:09

user2761220


1 Answers

You might defer the definition of B until A is fully defined, and defer C until both A and A.B are defined.

class A:
  a1 = 4

class B:
  b1 = A.a1
  b2 = 6
A.B = B
del B

class C:
  c1 = A.B.b2
A.C = C
del C

assert A.B.b1 == 4
assert A.C.c1 == 6

Alternatively, you could define B.b1 outside of B's definition:

class A:
  a1 = 4

  class B:
    pass
  B.b1 = a1
  B.b2 = 6

  class C:
    pass
  C.c1 = B.b2

assert A.B.b1 == 4
assert A.C.c1 == 6
like image 175
Robᵩ Avatar answered Oct 14 '22 16:10

Robᵩ