I am making a dictionay like app, and depending of the Translation switch, the screen displays the translation or the original word The code looks like this:
PS: "textFunction(text)" is just a function that displays text to screen. PS: "wordList" is a list of Word Class intances
class Word:
def __init__(self, original, translation):
self.original = original
self.translation = translation
translation = False
if translation == False:
wordDisplayed = .original
elif translation == True:
wordDisplayed = .translation
textFunction(wordList[X].wordDisplayed)
However, this doesn't work. How could I fix this?
CodePudding user response:
You would use getattr
:
wordDisplayed = "translation" if translation else "original"
textFunction(getattr(wordList[X], wordDisplayed))
CodePudding user response:
While "getattr" is a possible solution, I'd say adding a get
function to your class makes this all more readable and maintainable:
class Word:
def __init__(self, original, translation):
self.original = original
self.translation = translation
def get(self, translation):
return self.translation if translation else self.original
words = [Word("hello", "hallo"), Word("world", "Welt")]
for w in words:
print(w.get(False), w.get(True))
Output:
hello hallo
world Welt