【发布时间】:2018-10-16 22:54:41
【问题描述】:
我想将一些设置导入我当前的脚本,包含一个名为 settings.py 的外部模块。
目前,我在导入之前手动更改了“动物”变量。
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 个案例。我不能这样做,因为在我当前的设置中,我必须在导入之前手动更改“动物”变量。
如何将动物传递到设置中,以便我可以编写如下内容:
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)。我不知道在这里做什么。显然,实际用例更复杂。我真的希望我没有以这种方式逐个案例变量存储案例!
【问题讨论】:
-
即使同一个模块有多个
import语句,模块也只会导入一次。你有什么理由不想把它变成settings.get_animal('unicorn')? -
@Andreas Deak,这可能就是我一直在寻找的!您能否详细说明答案?我如何在现有的 settings.py 中构建类似“get_animal”的东西?
标签: python pandas python-import python-module