调用模块时,聪明的使用方式具有可变变量

问题描述 投票:0回答:1

我有3个不同的模块:

a.py

test_value = 19
........
.......
......
...... # more functions and I need to call every each of it or maybe inherit it

b.py

test_value = 20
....
...
.... #same many functions and each function will need to declare in c.py

我当前的实现。

c.py

在这里我称呼它

import a
import b

String = "I check A"

if "A" in String:
    first = a.test_value
    second = a.xxxxx
    third = a.yyyyy
    More continue
else:
    first = b.test_value
    second = b.xxxxx
    third = b.yyyyy
    More continue

我的期望。

import a
import b

String = "I check A"

if "A" in String:
    first = {}.test_value # the "a" could be replace with depending on the rules.
    ......more continue
else:
    first = {}.test_value # the same here.
    more......

我的方式可能是替换它的示例:

if "A" in String:
    replacement_value = a
else:
    replacement_value = b
first = "{}".format(replacement_value).test_value # the "a" could be replace with depending on the rules.
......more continue

这样,我可以重用代码并减少相似代码的数量,但是我收到了erorr:“ str'对象没有属性”

任何人都有更好的方法以便我学习吗?

python
1个回答
3
投票

您可以将模块分配给变量。

import a
import b

if <some condition>:
    module = a
else:
    module = b
# OR USE
module = a if "A" in String else b

# use it as
module.test_value

您可以将模块名称作为字符串,并使用其名称导入模块。

module_name = 'a' if 'A' in String else 'b'
module = __import__(module_name)

module.test_value

尝试这个例子。创建4个文件,a.py, b.py, c.py, d.py

a.py

x = 10

b.py

x = 20

c.py

import a
import b

x = input('Enter a value: ')
module = a if x == 'a' else b

print(module.x)

d.py

module = __import__('b')
print(module.x)

以下是输出:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.