问题,在python 3.7中构建交换机案例

问题,在python 3.7中构建交换机案例,python,python-3.x,Python,Python 3.x,我正试图在python 3.7中开发类似于switch case功能的东西,比如来自其他语言的knowen 为此,我在这里使用了本教程: 从以下代码开始: class ClassCheckShipping: def __init__(self): pass def __checkAktivweltShipping(self, country): return "checkShipping für Aktivwelt" def __ch

我正试图在python 3.7中开发类似于switch case功能的东西,比如来自其他语言的knowen

为此,我在这里使用了本教程:

从以下代码开始:

class ClassCheckShipping:

    def __init__(self):
        pass

    def __checkAktivweltShipping(self, country):
        return "checkShipping für Aktivwelt"

    def __checkHoerhelferShipping(self, country):
        return "checkShipping für Hörhelfer"

    def checkShipping(self, merchant, country):
        self.country = country
        switcher = {
            "Aktivwelt": __checkAktivweltShipping,
            "Hörhelfer": __checkHoerhelferShipping
        }
        func = switcher.get(merchant, lambda: "unbekannter Merchant")
        print(func())
不幸的是,我得到以下错误,我无法找到我的错误

CheckShipping中的第18行文件“M:\Python Projekte\Wipando Feeds\CheckShipping.py” “Aktivwelt”:u检查Aktivwelt装运, NameError:未定义名称“\u ClassCheckShipping\u checkAktivweltShipping”


您能给我一个提示来修复此代码吗?

您必须将
self
添加到
switcher
中的方法中:

switcher = {
    "Aktivwelt": self.__checkAktivweltShipping,
    "Hörhelfer": self.__checkHoerhelferShipping
}

您必须将
self
添加到
switcher
中的方法中:

switcher = {
    "Aktivwelt": self.__checkAktivweltShipping,
    "Hörhelfer": self.__checkHoerhelferShipping
}

你应该写:
self.\uu checkAktivweltShipping
self.\uu checkhoerfershipping
你应该写:
self.\uu checkAktivweltShipping
self.\uu checkhoerfershipping

另一种解决方案是将
切换器
定义为类成员(因为它是常量)然后您可以省略使用
self.

def __checkAktivweltShipping(self, country):
    return "checkShipping für Aktivwelt"

def __checkHoerhelferShipping(self, country):
    return "checkShipping für Hörhelfer"

__switcher = {
    "Aktivwelt": __checkAktivweltShipping,
    "Hörhelfer": __checkHoerhelferShipping
}
现在也必须使用
self
引用它,但是代码更简单(也更快,因为python不必在每次调用时都重新构建字典,在创建类时只执行一次)


另一种解决方案是将
switcher
定义为类成员(因为它是常量),然后可以省略使用
self。

def __checkAktivweltShipping(self, country):
    return "checkShipping für Aktivwelt"

def __checkHoerhelferShipping(self, country):
    return "checkShipping für Hörhelfer"

__switcher = {
    "Aktivwelt": __checkAktivweltShipping,
    "Hörhelfer": __checkHoerhelferShipping
}
现在也必须使用
self
引用它,但是代码更简单(也更快,因为python不必在每次调用时都重新构建字典,在创建类时只执行一次)


非常感谢你。很简单,非常感谢。很简单。很高兴我能帮忙。很高兴我能帮忙。