python - 在导入时将变量传递给自写模块?
问题描述
我想将一些设置导入我当前的脚本,包含一个名为 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)。我不知道在这里做什么。显然,实际用例更复杂。我真的希望我没有通过以这种方式逐个变量存储案例而使自己陷入困境!
解决方案
这最好通过调用外部模块中的函数来完成。可以这样做:
设置.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”]
.
推荐阅读
- javascript - 使用 Angular 4 上传文件
- html - FontAwesome 从 4 升级到 5 (Tumblr)
- javascript - reactjs 如何处理数组内部的状态变化?(对 Select 元素使用 antd 设计)
- c# - Nmodbus 返回 NotImplementedException: Function code 123 not supported exception while reading response data
- java - 使用 Spring Boot 在 TestNg 测试用例中提供 BeanFactory Bean
- guile - 配置说没有找到 guile-config
- django - 如何进行查询以获取 Django ORM 中每个组的最后一个元素?
- python - 在 Python 中对来自不同类别的 n 长度数组的分类数据进行编码
- heroku - 在 Heroku 上使用 Redis 的服务器端 Flask 会话
- jquery - 如何使用输入文本和选择对数据表应用高级搜索?