Ben*_*min 4 python methods dictionary subscript
我已经读过一个关于(非)可订阅对象的线程,但是它没有告诉我该怎么做。
我有一个代码调用mypost私有模块。目的是建立邮件帐户,并为此创建模块中MailAccounts()定义的对象mypost。配置文件中描述了帐户数量及其各自的详细信息。当应用程序启动时,它将收集帐户信息并将其存储在字典中,该字典的结构为:accounts = {service : { <MailAccounts Object at xxxxx> : {username : myusername, password : mypassword}}}其中service可以是“ gmail”,而模块中MailAccounts定义的类在哪里mypost。到目前为止,一切都很好。但是,当我要设置帐户时,需要调用其方法:MailAccounts.setupAccount(username, password)。我通过迭代字典的每个MailAccount对象并要求运行该方法来执行此操作:
for service in accounts:
for account in accounts[service]:
account.setupAccount(account['username'], account['password'])
Run Code Online (Sandbox Code Playgroud)
但是您可能已经猜到它没有用,Python返回:
TypeError: 'MailAccount' object is not subscriptable
如果我手动创建相同的帐户,则可以:
account = MailAccount()
account.setupAccount('myusername', 'mypassword')
Run Code Online (Sandbox Code Playgroud)
现在,我相信这与我<MailAccount Object at xxxx>是词典密钥有关吗?这使得它不可订阅(可能意味着什么)?
不,这到底是什么意思不可订阅?在此示例中意味着什么?当然,在这种情况下,我该如何解决/绕过此问题?
谢谢,本杰明:)
解决它的方法是正确使用字典。
for service in accounts:
for account, creds in accounts[service].iteritems():
account.setupAccount(creds['username'], creds['password'])
Run Code Online (Sandbox Code Playgroud)