我定义了一个类,并用它来初始化变量。当我在函数中使用此变量时,它会全局更改(即使函数未将其返回)。我发现这很奇怪,但是在这里得到了解释:Python class is changing global variable without declaring it global。但是,我想知道是否有一种方法可以使我的变量在函数中成为局部变量。这样,我可以在函数之后使用它,并且它具有与调用函数之前相同的值。这是我的代码:
# Definition of a class allowing to use structures (like in Matlab)
class structtype():
pass
# Creation of a structure
x = structtype
# Creation of an item in the structure
x.item = 10
# Creation of a function using the structure
def func(x):
x.item = 20
func(x)
print(x.item) # returns 20 whilst I want 10
在上面的示例中,我希望在使用该函数后x.item
保持10,但它保留了该函数中分配的值。
x = structtype
不创建实例。它为structtype
类提供了另一个名称x
。您需要
x = structtype()