Reputation: 21
I am trying to develop something like a switch-case functionality, like knowen from other language, in python 3.7.
For that, I used this tutorial here: https://jaxenter.com/implement-switch-case-statement-python-138315.html
and started with this code:
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())
Unfortunately, i get the following error and i can't find my mistake.
File "M:\Python-Projekte\Wipando-Feeds\CheckShipping.py", line 18, in checkShipping "Aktivwelt": __checkAktivweltShipping, NameError: name '_ClassCheckShipping__checkAktivweltShipping' is not defined
Can you please give me a hint to fix this code?
Upvotes: 1
Views: 1034
Reputation: 140297
an alternate solution would be to define switcher
as a class member (since it's constant) then you can omit to use 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
}
now it must be referenced using self
too, but the code is simpler (also faster because python doesn't have to rebuild the dictionary at each call, it's only done once, when creating the class)
def checkShipping(self, merchant, country):
self.country = country
func = self.__switcher.get(merchant, lambda: "unbekannter Merchant")
print(func())
Upvotes: 2
Reputation: 1628
you should write: self.__checkAktivweltShipping
and self.__checkHoerhelferShipping
Upvotes: 3
Reputation: 36732
You must add self
to the methods in switcher
:
switcher = {
"Aktivwelt": self.__checkAktivweltShipping,
"Hörhelfer": self.__checkHoerhelferShipping
}
Upvotes: 4