首页 > 解决方案 > 在导入时将变量传递给自写模块?

问题描述

我想将一些设置导入我当前的脚本,包含一个名为 settings.py 的外部模块。

目前,我在导入之前手动更改了“动物”变量。

设置.py

animal='Unicorn' #I want to get rid of this line, and pass the variable during the import.

if animal=='Unicorn':
        fur_color='sparkles'
        number_of_legs=4

if animal=='Centipede':
    fur_color='black'
    number_of_legs=100

if animal =='Cat':
    fur_color='brown'
    number_of_legs=4

我跑:

from settings import fur_color, number_of_legs

并拥有所需的信息。

但是,我现在需要遍历这 3 个案例。我不能这样做,因为在我当前的设置中,我必须在导入之前手动更改“动物”变量。

如何将动物传递到设置中,以便我可以编写如下内容:

for animal in animals:
    from settings import *
    print('A' + animal + ' has ' + str(number_of_legs) + ' and is ' + fur_color)

期望的输出是:

A Unicorn has 4 legs and is sparkles
A Centipede has 100 legs and is black
A Cat has 4 legs and is brown.

循环内的“导入”不会更新设置,也不会使用 imp.reload(settings)。我不知道在这里做什么。显然,实际用例更复杂。我真的希望我没有通过以这种方式逐个变量存储案例而使自己陷入困境!

标签: pythonpandaspython-importpython-module

解决方案


这最好通过调用外部模块中的函数来完成。可以这样做:

设置.py:

def animal_info(animal):
    if animal=='Unicorn':
        fur_color='sparkles'
        number_of_legs=4
    elif animal=='Centipede':
        fur_color='black'
        number_of_legs=100
    elif animal =='Cat':
        fur_color='brown'
        number_of_legs=4
    return fur_color, number_of_legs

然后,在您的主模块或交互式提示中,您可以使用它:

import settings
for animal in animals:
    fur_color, number_of_legs = settings.animal_info(animal)
    print('A' + animal + ' has ' + str(number_of_legs) + ' and is ' + fur_color)

如果您正在使用比这更大的数据表,那么您可能需要考虑使用pandas数据框。只需将您的数据存储在逗号分隔或制表符分隔的文本文件中,然后使用 读取它,df = pandas.read_csv(....)根据您的查找列设置索引,然后访问df.loc[animal, “number of legs”].


推荐阅读