你好開發商,全局變量不工作蟒蛇
我寫的代碼,將用戶輸入並初始化根據輸入的一類像下面的示例代碼:
class X:
def __init__(self):
return
def run(self):
print("i am X")
def func1(cls):
exec("global " + cls.lower())
exec(cls.lower() + " = " + cls + "()")
def func2(mode_to_set):
exec(mode_to_set.lower() + ".run()")
但我運行這樣的代碼:
我不斷收到此錯誤:
Traceback (most recent call last):
File "/Users/noahchalifour/Desktop/test.py", line 16, in <module>
func2('X')
File "/Users/noahchalifour/Desktop/test.py", line 13, in func2
exec(mode_to_set.lower() + ".run()")
File "<string>", line 1, in <module>
NameError: name 'x' is not defined
任何人都可以幫助我嗎?
該變量需要已經存在於全局範圍內。此外,這是一個可怕的想法。另外,你正在嘗試創建一個'x'的實例,但是你的類被稱爲'X'。 –
爲什麼這麼糟糕? @MorganThrapp –
可能的重複[如何在Python中創建可變數量的變量?](http://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables在python) –