简体   繁体   English

从另一个嵌套类访问属性

[英]Accessing attributes from another nested class

I would like to achieve something similar to this construction: 我想实现类似于此构造的东西:

class Outer:
    class A:
        foo = 1

    class B:
        def __init__(self):
            self.bar = A.foo

Outer.B().bar  # ==> 1

But this fails with 但这失败了

NameError: name 'A' is not defined

I'm not even sure I understand why as A is (I thought) in scope. 我甚至不知道我的理解,为什么作为A是(我认为)的范围。

Could you help me clarify why this doesn't work and how I could get around it? 您能帮我弄清楚为什么这行不通以及如何解决吗?

Names are looked up only in globals , locals , and nonlocal cells (but you don't have a closure here). globalslocals和nonlocal单元格中查找名称(但这里没有闭包)。

Write Outer.A instead of A , or consider making Outer a module. Outer.A而不是A ,或考虑将Outer模块。

如果您使用Outer.A.foo它将起作用。

就像您对Outer.B().bar所做的操作一样:对self.bar=Outer.A().foo也做相同的self.bar=Outer.A().foo

Inner classes in Python do not have acces to the members of the enclosing class. Python中的内部类没有访问该封闭类的成员的权限。 A is not in scope of B as you state. 如您所声明的,A不在B的范围内。 A and B are both in scope of Outer, but they do not know of each other. A和B都在“外部”范围内,但彼此之间不认识。 Therefore a possible solution to your problem: 因此,可以解决您的问题:

class Outer:
    class A:
        foo = 1

    class B:
        def __init__(self, class_a):
            self.bar = class_a.foo

    def __init__(self):
        self.a = self.A()
        self.b = self.B(self.a)


print(Outer.A.foo) # 1
print(Outer.B.bar) # AttributeError: type object 'B' has no attribute 'bar'

outer = Outer()
print(outer.a.foo)  # 1
print(outer.b.bar)  # 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM