class 中的函数中的变量是否在 Python 中包含在 class 中的所有其他函数之间共享?
Are variables in the function within a class shared between all other functions enclosed in that class in Python?
我知道 class 属性是共享的,并且可以被包含在同一个 class 中的所有函数访问,但我的问题是包含在 class 中的函数中的变量呢?
我正在尝试创建一个 GUI,而我的 class 仅由函数组成。
class Application():
def func_a(self):
self.x = Entry(text="My entry text")
def func_b(self):
self.x.config(width=100)
这行得通吗?如果第一个函数中的 self.x
变量在同一个 class 中,它们会被 func_b
引用吗? Python如何处理不同函数中的变量都包含在同一个class中?我想他们会被分享,但我不知道。
Can this work? Will the self.x variable in the first function be referred to by func_b if they're in the same class?
当然可以。但是由于变量 x
只在 func_a
中创建,所以它应该在 func_b
被调用之前被调用。否则会报错。
How does Python deal with variables in different functions all enclosed in the same class? I suppose they will be shared
由于实例变量特定于它们在其中定义的实例,因此它们将可用于 class 中的所有方法。在你的情况下,当你这样做时
self.x = ...
您实际上是在 self
引用的当前实例中创建了一个名为 x
的属性。因此,如果您使用同一个实例调用 func_b
,它将正常工作。例如,
# Create an instance
app = Application()
# Call `func_a` to create `x` in `app`
app.func_a()
# Check if it is present
print(app.x)
# Call `func_b` and now it should not fail
app.func_b()
编辑: 正如加布里埃尔在评论中提到的那样,尝试在 __init__
(构造函数)本身中创建实例变量,这样您就不必担心函数调用的顺序。
我知道 class 属性是共享的,并且可以被包含在同一个 class 中的所有函数访问,但我的问题是包含在 class 中的函数中的变量呢?
我正在尝试创建一个 GUI,而我的 class 仅由函数组成。
class Application():
def func_a(self):
self.x = Entry(text="My entry text")
def func_b(self):
self.x.config(width=100)
这行得通吗?如果第一个函数中的 self.x
变量在同一个 class 中,它们会被 func_b
引用吗? Python如何处理不同函数中的变量都包含在同一个class中?我想他们会被分享,但我不知道。
Can this work? Will the self.x variable in the first function be referred to by func_b if they're in the same class?
当然可以。但是由于变量 x
只在 func_a
中创建,所以它应该在 func_b
被调用之前被调用。否则会报错。
How does Python deal with variables in different functions all enclosed in the same class? I suppose they will be shared
由于实例变量特定于它们在其中定义的实例,因此它们将可用于 class 中的所有方法。在你的情况下,当你这样做时
self.x = ...
您实际上是在 self
引用的当前实例中创建了一个名为 x
的属性。因此,如果您使用同一个实例调用 func_b
,它将正常工作。例如,
# Create an instance
app = Application()
# Call `func_a` to create `x` in `app`
app.func_a()
# Check if it is present
print(app.x)
# Call `func_b` and now it should not fail
app.func_b()
编辑: 正如加布里埃尔在评论中提到的那样,尝试在 __init__
(构造函数)本身中创建实例变量,这样您就不必担心函数调用的顺序。