python:嵌套类:访问外部类的类成员 [英] python: nested classes: access outer class class member

查看:93
本文介绍了python:嵌套类:访问外部类的类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不起作用:

class A:
  a1 = 4

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

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

有任何非神秘的方法可以解决吗?我知道我可以从A中取出B和C,但我想保留它们.我还认为没有类成员会更容易,因为它们可以轻松地作为构造函数中的参数传递给嵌套类,但是作为所有这些类成员,我不知道如何在这里做类似的事情.我还在某个线程上读到了这种用法,它记得使用类作为名称空间,应该使用模块而不是类来解决,但是上面的类对我来说是真实的类(我构造实例),另外还要共享类数据其中.

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.

推荐答案

您可以将 B 的定义推迟到完全定义 A 之前,并推迟 C,直到同时定义了 A AB .

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

或者,您可以在 B 的定义之外定义 B.b1 :

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

这篇关于python:嵌套类:访问外部类的类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆