在导入时将变量传递给自写模块?

Pass Variable to Self-Written Module on Import?

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

目前,我在导入前手动更改 'animal' 变量。

settings.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 个案例。我不能这样做,因为在我当前的设置中,我必须在导入之前手动更改 'animal' 变量。

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

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.

循环中的 "import" 不会更新设置,使用 imp.reload(settings) 也不会。我不知道在这里做什么。显然,实际用例要复杂得多。我真的希望我没有因为以这种方式存储个案变量而搬起石头砸自己的脚!!

模块只导入一次,即使以后有相同模块的导入也是如此。这意味着我不希望有一种简单的方法来处理您当前的设置。

我建议在 settings 中定义一个函数,它将根据其字符串输入生成您想要的配置:

def get_animal(kind):
    if kind == 'Unicorn':
        fur_color = 'sparkles'
        number_of_legs = 4
    elif kind == 'Centipede':
        fur_color = 'black'
        number_of_legs = 100
    elif kind == 'Cat':
        fur_color = 'brown'
        number_of_legs = 4
    else:
        raise ValueError(f'Invalid animal {kind}!')
    #return dict(fur_color=fur_color, number_of_legs=number_of_legs)
    # or
    return fur_color, number_of_legs

然后就可以得到对应的dict为

from settings import get_animal
for animal in animals:
    animal_dict = get_animal(animal)
    # animal_dict['fur_color'] etc. can be accessed
    print('A {animal} has {number_of_legs} legs and is {fur_color}'.format(
         animal=animal, **animal_dict))

当然,如果您的用例不太适合 dict,您可以使用元组 return 值定义函数,然后解压缩:

from settings import get_animal
for animal in animals:
    fur_color,number_of_legs = get_animal(animal)
    # do complicated stuff here

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

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

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