[英]Access variables from another module by their name
我有一個模塊A.py
,在其中聲明了所有需要的變量:
dog_name = ''
dog_breed = ''
cat_name = ''
cat_breed = ''
# .....
我在其中導入A的文件為B.py。我知道如何訪問在A中定義的變量:
import A
A.dog_name = 'gooddog' # I am able to use A in file B
A.cat_name = 'goodcat'
print(A.dog_name) # this is working fine
但是我希望用戶輸入要訪問的變量的名稱,例如“ cat_name”或“ dog_name”。
x = input('Which variable do you want to read') # could be cat_name or dog_name
# This fails:
print(A.x) # where x should resolve to cat_name and print the value as goodcat
有什么辦法可以實現?
您可以將getattr
與模塊一起使用:
import A
getattr(A, 'dog_name')
# ''
和setattr
,以及:
setattr(A, 'dog_name', 'fido')
getattr(A, 'dog_name')
# 'fido'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.