Reputation: 234
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 gives me a syntax error. How could I code this?
Upvotes: 0
Views: 110
Reputation: 10782
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
Upvotes: 0
Reputation: 532003
You would use getattr
:
wordDisplayed = "translation" if translation else "original"
textFunction(getattr(wordList[X], wordDisplayed))
Upvotes: 5