简体   繁体   English

将Python参数传递给模块

[英]Passing a Python argument to a module

Simple NOOB question, but after an hour of searching I still can't find it. 简单的NOOB问题,但经过一个小时的搜索我仍然找不到它。 In Python 3.6 I've got a working module nhcparams with a dictionary, FOO. 在Python 3.6中,我有一个带有字典的工作模块nhcparams,FOO。 The following code is tested and works: 以下代码经过测试并可用:

import nhcparams

def get_max_price():
    my_price = nhcparams.FOO['Price']

I'd like to change it to: 我想把它改成:

import nhcparams

def get_max_price(ARG):
    my_price = nhcparams.ARG['Price']

get_max_price(FOO)

That doesn't work, which I am hoping is just a syntax problem on my end. 这不起作用,我希望这只是我的语法问题。 Any help getting me past my idiocy would be appreciated :) 任何帮助让我超越我的愚蠢的人将不胜感激:)

You can use the getattr function to dynamically access attributes in your module: 您可以使用getattr函数动态访问模块中的属性:

import nhcparams

def get_max_price(ARG):
    my_price = getattr(nhcparams, ARG)['Price']

get_max_price('FOO')

Notice that 'FOO' needs to be passed as a string. 请注意,'FOO'需要作为字符串传递。 And the attribute is returned from the getattr function call 并且该属性从getattr函数调用返回

Try this 尝试这个

import nhcparams

def get_max_price(ARG):
    my_price = ARG['Price']
    # Do stuff

get_max_price(nhcparams.FOO)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM