简体   繁体   中英

How to import objects from another module as a list

in moduleA.py:

A = 1
B = 2
C = 3
D = 4

in moduleB.py, how can I achieve:

from moduleA import (A, B, C, D) as nums

for x in nums:
    print(x)

You can't do this the way you are trying to. You will need to find a different solution to your original problem.

Are you looking for something like this?

$ cat moduleB.py
#!/usr/bin/env python

import moduleA

for x in ['A', 'B', 'C', 'D']:
        print(getattr(moduleA, x))

$ ./moduleB.py
1
2
3
4
import a
from a import A,B,C,D

lst = [A, B, C, D]
print('List of nums from a.py is: ' + str(lst))

print('Elements in list:')
for x in lst:
    print(x)

Result:

'''
List of nums from a.py is: [1, 2, 3, 4]
Elements in list:
1
2
3
4
'''

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