[英]Python- get parent class function instant variables from within a nested class
I'm having a bit of a dilemma with Python nested classes. 我在使用Python嵌套类时遇到了两难选择。 What i'm trying to do is get variables from a function at the top level of class A and use them in the sub class B. Something like this 我想做的是从类A的顶级函数中获取变量,并在子类B中使用它们。类似这样的事情
class A:
def function_A():
value = 5
class B:
def function_B(self):
print (A.value)
This method below works if i turn the variable into a class variable like below but it doesn't do what i want: 如果我将变量转换为如下所示的类变量,则下面的此方法有效,但它无法实现我想要的功能:
class A:
value = 5
class B:
def function_B(self):
print (A.value)
I'm guessing that this isn't possible so can anyone provide a workaround? 我猜这是不可能的,所以任何人都可以提供解决方法吗?
The variable value
is local to function_A
, and exists only while that method is running. 变量value
是function_A
局部变量,仅在该方法运行时存在。 There is simply nothing to access when it's not executing, which will be the case when function_B
is executing. 不执行时根本没有访问权限,这是在function_B
执行时的情况。 In particular, in your first example it's not an attribute of A
, or of any instance of A
. 特别是,在你的第一个例子中它不是一个属性A
,或任何情况下的A
。
It's not clear from your code what you actually intend to do with such a value
, so it's difficult to make further suggestions. 从您的代码中尚不清楚使用此value
实际打算做什么,因此很难提出进一步的建议。
The class A has no attribute value
, because the value
variable is defined inside the function_A
function. 类A没有属性value
,因为value
变量是在function_A
函数内部定义的。 Therefore you don't have to access value
as an attribute of the class, but as a normal variable that you can access from class B
, because it is in the same scope. 因此,您不必将value
作为类的属性来访问,而可以作为可从类B
访问的普通变量来访问,因为它在同一范围内。 You have to remove the A.
before value
您必须先删除A.
value
Example: 例:
class A:
def function_A():
value = 5
class B:
def function_B():
print (value)
var = B
var.function_B()
test = A
test.function_A()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.