我在调用一个子函数外的变量时遇到了问题。
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'
for C = self.B
如何让self.B从外部访问?
非常感谢:)
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__
上一个答案。
你从未调用过你的 "子函数"
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的唯一方法是让函数运行,即使它是嵌套的......这是一种奇怪的设置类的方法,但你会发现