如何访问 class 中子函数的变量?

How to access variables of a sub-function in a class?

我在调用子函数外的变量时遇到问题:

class ABC():
    def ___init___(self):
        function_A()
        function_B()
    def function_A(self):
        self.A = 5
        def subfunction_of_A(self):
            self.B = 2
            self.function_B()
        subfunction_of_A()
    def function_B(self):
        C = self.B

 Start = ABC()

我总是得到错误: 'ABC' object has no attribute 'B' 对于 C = self.B

如何让 self.B 可以从外部访问?

非常感谢:)

-------- EDIT/UPDATE ---------- 好的,我想我可能需要稍微更新一下我的问题:

class ABC():
    def ___init___(self):
        self.function_A()
        self.function_B()
    def function_A(self):
        self.A = 5
        def subfunction_of_A(self):
            self.B = 2
        subfunction_of_A(self)
        print(self.B) # This prints 2 and works as it should!
    def function_B(self):
        C = self.B # In this line I receive the error that ABC.B does not exist --> Why is that?

 Start = ABC()

编辑:

class ABC():
    def __init__(self):
        self.function_A()
        self.function_B()
    def function_A(self):
        self.A = 5
        def subfunction_of_A(self):
            self.B = 2
        subfunction_of_A(self)
    def function_B(self):
        print(self.B) # This prints 2 and works as it should!
        C = self.B

Start = ABC()

这次你的问题似乎是你的 ___init___ 有 3 个下划线而不是 2 个... __init__

上一个回答:

你永远不会打电话给你的 "sub function"

class ABC():
    def function_A(self):
        self.A = 5
        def subfunction_of_A(self):
            self.B = 2
        subfunction_of_A(self) # notice this line

    def function_B(self):
        self.C = self.B


abc = ABC()
abc.function_A()
abc.function_B()
print(abc.C) # prints 2

设置 B 的唯一方法是将该函数设置为 运行,即使它是嵌套的...这是一种设置 class 的奇怪方法,但是你去