Python:类中的字典变量

标签 python

我正在尝试使用字典方法创建一个“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/

相关文章:

python - 如何在 python 中拆分一串数学表达式?

python - 使用 Tensorflow 中的索引为 2D 张量赋值

javascript - Bokeh python ;使用 ColumnDataSource 上的回调来更改带有 Select Widget 的堆叠条形图

python - matplotlib如何用定义的颜色绘制多条线?

python - 在 pandas 中合并表时添加默认值

python - Ruby-OpenSSL、PyCrypto 之间的 AES 加密/解密

python - CPython 中 os.stat() 在哪里定义?

python - 为什么 sklearn KMeans 在拟合后会更改我的数据集?

python - python中的最小子数组差异

python - 在 Python 中将列中的数字相加无法正常工作?