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

如何通过变量引用其他模块中的Python对象?遇AttributeError报错

问题描述

我在weapon.py中定义了Weapon类,并实例化了axe对象。在main.py中,直接使用import weapon后执行cur_weapon = weapon.axe可以成功获取axe对象并使用;但当定义字符串变量cur_choice = "axe",尝试通过cur_weapon = weapon.cur_choice引用时,触发错误:AttributeError: module 'weapon' has no attribute 'cur_choice'。请问是否需要进行某种“解引用”操作?同时希望了解该问题的技术描述方式(我是Python新手)。

可行的main.py代码

import weapon

cur_weapon = weapon.axe
print(cur_weapon)

报错的main.py代码

import weapon

cur_choice = "axe"
cur_weapon = weapon.cur_choice
print(cur_weapon)

weapon.py代码

from random import randint
class Weapon:
    """initalize weapon, defaults to the humble dagger"""
    def __init__(
        self,
        name = "humble dagger",
        two_hand = False,
        die_dmg = 6,
        rolls = 1,
        magic_mod = 0,
        dmg_type  = "slash",
        speed = 0,
        dur = 100,
        wid = 99
    ):
        self.name = name
        self.two_hand = two_hand
        self.die_dmg = die_dmg
        self.rolls = rolls
        self.magic_mod = magic_mod
        self.dmg_type = dmg_type
        self.speed = speed
        self.dur = dur
        self.wid = wid

    def attack_dmg(self):
        hit = (randint(1, self.die_dmg) * self.rolls) + self.magic_mod
        print(f"Your {self.name} hits for {hit} damage")
        return hit

axe = Weapon("axe", False, 6, 2, 0, "slash", 100, 0, 101)

解决方案

你需要用Python内置的getattr()函数实现通过字符串动态访问模块属性,修改后的代码如下:

import weapon

cur_choice = "axe"
cur_weapon = getattr(weapon, cur_choice)
print(cur_weapon)

原写法报错原因

当你写weapon.cur_choice时,Python会直接在weapon模块中查找名为cur_choice的属性,但你定义的cur_choice是本地变量,并非模块的属性,因此触发AttributeError。而getattr()的作用就是动态获取对象(此处为模块对象)的属性,第一个参数是目标对象,第二个参数是属性名的字符串,刚好满足你通过字符串变量获取对应属性的需求。


技术描述方式

这个问题属于动态属性访问场景:在运行时通过字符串形式的属性名,获取对象(模块、类、实例等)的属性或方法。Python不支持直接将变量名作为属性访问的标识符,必须借助getattr()这类动态访问工具实现。你遇到的AttributeError,是Python尝试访问对象不存在的属性时抛出的标准内置异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:55:54