You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何根据开关动态访问Word类实例的对应属性解决语法报错

问题解决方法

你代码出现语法错误是两个原因导致的:

  • 单独写.original/.translation是非法Python语法,前置点只能跟在实例对象后面,不能作为独立值赋值给变量
  • 点语法默认会把后面的内容当作属性的固定名称,不会解析变量存储的动态值,因此不能用实例.变量名的方式读取动态属性

方案1:直接分支判断(最直观,推荐优先使用)

直接根据翻译开关的状态,从目标单词实例中读取对应属性即可:

class Word:
  def __init__(self, original, translation):
      self.original = original
      self.translation = translation

# 翻译开关
translation_switch = False
# X为单词列表的目标索引,替换为你的实际值
target_word = wordList[X]

if translation_switch:
    display_content = target_word.translation
else:
    display_content = target_word.original

textFunction(display_content)

可以进一步简化为三目表达式写法:

display_content = target_word.translation if translation_switch else target_word.original

方案2:动态属性读取(符合你最初的代码思路)

如果需要把属性名存入变量再读取,要使用Python内置的getattr()函数实现反射调用:

translation_switch = False
# 先存储要读取的属性名字符串
attr_name = "translation" if translation_switch else "original"
# 动态读取对应属性
display_content = getattr(wordList[X], attr_name)

textFunction(display_content)

getattr(实例对象, 属性名字符串)会自动从实例中取出对应名称的属性值,完美适配动态属性读取的场景。


内容的提问来源于stack exchange,提问作者Peter Petigru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:54:03