我正在尝试使用字典方法创建一个“switch”语句。我可以在没有类(class)的情况下做到这一点,但是有了类(class),无论我尝试什么类型的咒语,我似乎都无法使其发挥作用。
#!/usr/bin/python3
import numpy as np
import sys
def func1(var1):
print("hi guy")
return 0
Mycode = { 5:func1 }
indx1 = 5
var1 = 0
temp = Mycode[indx1]
temp(var1)
sys.exit()
The above code works.
The code below does not work
#!/usr/bin/python3
import numpy as np
import sys
class Beef():
def __init__(self):
junk = 3
def func1(self, var1):
print("hi guy")
return 0
def find(self):
self.Mycode = { 5:func1 }
self.run()
def run(self):
indx1 = 5
var1 = 0
temp = self.Mycode[indx1]
errcode = temp(0)
sys.exit()
hvfbeef = Beef()
hvfbeef.find()
我收到错误“NameError:名称'func1'未定义”,尽管在其他排列中我收到其他错误。 我似乎不明白字典在类和函数中是如何工作的。 任何帮助将不胜感激。
最佳答案
self.Mycode = { 5:self.func1 }
^^^^
应该是自己。
另外,
temp = self.Mycode[indx1]
^^^^
关于Python:类中的字典变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35169253/