简体   繁体   中英

Passing a Python argument to a module

Simple NOOB question, but after an hour of searching I still can't find it. In Python 3.6 I've got a working module nhcparams with a dictionary, 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:

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. And the attribute is returned from the getattr function call

Try this

import nhcparams

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

get_max_price(nhcparams.FOO)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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