简体   繁体   English

调用python中的变量定义

[英]call defining by variable in python

I have two files 我有两个档案

test_def.py
def hi_test(a):
    return a

test_run.py test_run.py

from test_def import hi_test
a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
run1 = run(c)
print run1

it is printing hi_test(lion) instead of executing / calling def function. 它正在打印hi_test(lion)而不是执行/调用def函数。 can anyone help on this to execute the def function ? 任何人都可以帮助执行def功能吗?

import test_def
a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
run1 = getattr(test_def, run)(c)
print run1

it can be archive by the following method. 可以通过以下方法将其存档。

import test_def
a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
run1 = getattr(test_def,run)
run2 = run1(c)
print run2

test_def.py test_def.py

def hi_test(a):
    print a

test_run.py test_run.py

from test_def import hi_test

a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
exec("%s('%s')"%(run, c))

Although, the first answer is better 虽然,第一个答案更好

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

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