我的文件很少 setting.py
company='google'
另一个文件google.py
details = {'location':'usa', 'stock':948}
和main.py
import setting
print setting.company
profile = __import__(setting.company)
print profile.details
class test():
def pd (self,details):
self.param=details
print self.param
print profile.details
print profile.details['stock']
self.next_method()
def next_method(self):
print "in next_method"
print profile.self.param
t1=test()
t1.pd('details')
当我尝试使用go从google.py打印dict变量时,它会给我一个错误。 我需要得到字典变量。我的脚本o / p是
python main.py
google
{'location': 'usa', 'stock': 948}
details
{'location': 'usa', 'stock': 948}
948
in next_method
Traceback (most recent call last):
File "main.py", line 18, in <module>
t1.pd('details')
File "main.py", line 12, in pd
self.next_method()
File "main.py", line 15, in next_method
print profile.self.param
AttributeError: 'module' object has no attribute 'self'
答案 0 :(得分:0)
我认为你所做的事情是一件非常奇怪的事情,应该避免你试图做的动态导入。您尝试创建的内容可能会以更好的方式完成(例如,为什么不是单个配置文件中的所有信息?)。尽管如此:
from pprint import pprint
import setting
profile = __import__(setting.company).details
class Company(object):
def __init__(self, name, details):
self.name = name
self.details = details
def printDict(self):
print(self.name+'\n============\n')
pprint(self.details)
t1 = Company(setting.company, profile)
t1.printDict()