简体   繁体   中英

Python - Assign class attribute to a variable

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?

You would use getattr :

wordDisplayed = "translation" if translation else "original"
textFunction(getattr(wordList[X], wordDisplayed))

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM