簡體   English   中英

Python - 將類屬性分配給變量

[英]Python - Assign class attribute to a variable

我正在制作一個類似應用程序的字典,根據翻譯開關,屏幕顯示翻譯或原始單詞代碼如下所示:

PS:“textFunction(text)”只是一個將文本顯示到屏幕的函數。 PS:“wordList”是詞類實例列表

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)

但是,這不起作用。 我怎么能解決這個問題?

你會使用getattr

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

雖然“getattr”是一個可能的解決方案,但我想說在你的類中添加一個get函數會使這一切更具可讀性和可維護性:

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))

輸出:

hello hallo
world Welt 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM