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

为何无法用字符串运算符导入模块变量?Python动态调用方案求助

Dynamic Access to Fruit Variables in Python

Hey there! Let's figure out how to solve this dynamic variable access problem you're facing. The issue with your initial attempts is either not targeting the right module with getattr() or relying on scattered variables that make dynamic access clunky. Here are two solid solutions:

1. Fix the getattr() Approach (If You Want to Keep Existing Variables)

If you prefer to stick with your current variable setup in VariableScript.py, you just need to correctly reference the module when using getattr().

First, here's what your VariableScript.py might look like:

# VariableScript.py
variableColorApple = "red"
variableWeightApple = 150
variableColorBanana = "yellow"
variableWeightBanana = 120

In your other script, import the module and build the variable name dynamically, then use getattr() to fetch it from the module:

import VariableScript

# Get user input
selected_fruit = input("Enter a fruit (e.g., Apple): ")

# Build the variable name string
color_var_name = f"variableColor{selected_fruit}"

try:
    # Fetch the variable from the imported module
    fruit_color = getattr(VariableScript, color_var_name)
    print(f"The color of {selected_fruit} is {fruit_color}")
except AttributeError:
    # Handle cases where the fruit has no defined variable
    print(f"Sorry, no color data found for {selected_fruit}")

This works because getattr() needs to know which object (in this case, the VariableScript module) to look for the attribute in. Your earlier attempt probably missed specifying the module, which is why it couldn't find the variable.

2. Use a Dictionary (The More Pythonic Solution)

Honestly, scattered variables like variableColorApple are hard to maintain and error-prone. A better approach is to restructure your data into a dictionary in VariableScript.py—this makes dynamic access straightforward and your code cleaner.

Update VariableScript.py to use a dictionary:

# VariableScript.py
fruit_database = {
    "Apple": {
        "color": "red",
        "weight": 150
    },
    "Banana": {
        "color": "yellow",
        "weight": 120
    },
    # Add more fruits here as needed
}

Then in your other script, you can directly access the data using the user's input as a dictionary key:

from VariableScript import fruit_database

selected_fruit = input("Enter a fruit (e.g., Apple): ")

if selected_fruit in fruit_database:
    print(f"The color of {selected_fruit} is {fruit_database[selected_fruit]['color']}")
else:
    print(f"Sorry, no data found for {selected_fruit}")

This method is way more scalable—adding a new fruit just means adding a new entry to the dictionary, no need to create new variables. It also avoids the need for try/except blocks (you can use a simple in check) and makes your code easier to read for other developers.


内容的提问来源于stack exchange,提问作者o.d.rinani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:25:16