Python:如何处理不可订阅的对象?
我读过一个线程关于(不可)可订阅对象是什么,但它并没有告诉我我可以对此做什么。
我有一个调用 mypost
私有模块的代码。目的是设置邮件帐户,为此我创建了 mypost
模块中定义的 MailAccounts()
对象。帐户的数量及其各自的详细信息在配置文件中描述。当应用程序启动时,它会收集帐户信息并将其存储在字典中,其结构为: accounts = {service : {
其中 service
可以是“gmail”,其中 MailAccounts
是 mypost 中定义的类模块。 到目前为止,一切都很好。然而,当我想设置帐户时,我需要调用它的方法:
MailAccounts.setupAccount(username,password)
。我通过迭代字典的每个 MailAccount 对象并要求运行该方法来做到这一点:
for service in accounts:
for account in accounts[service]:
account.setupAccount(account['username'], account['password'])
但正如您可能已经猜到的那样,它不起作用,Python 返回:
TypeError: 'MailAccount' object is not subscriptable
如果我手动创建相同的帐户,但它的工作原理:
account = MailAccount()
account.setupAccount('myusername', 'mypassword')
现在我相信这与我的
是字典键这一事实有关,对吗?这使得它不可订阅(无论这意味着什么)?
不,不可订阅到底意味着什么?在这个例子中它意味着什么?当然:在这种情况下我该如何解决/绕过这个问题?
谢谢, 本杰明:)
I've read a thread on what a (non)subscriptable object is but it doesn't tell me what i can do about it.
I have a code calling a mypost
private module. The aim is to set up mail accounts and to do this i create MailAccounts()
objects defined in the mypost
module. Quantity of accounts and their respective details are described in a configuration file. When the application starts, it collects account information and stores it in a dictionary, the structure of which is: accounts = {service : { <MailAccounts Object at xxxxx> : {username : myusername, password : mypassword}}}
where service
can be "gmail" and where MailAccounts
is the class defined in the mypost
module.
So far so good. When however i want to setup the account, i need to call its method: MailAccounts.setupAccount(username, password)
. I do this by iterating each MailAccount object of the dictionary and ask to run the method:
for service in accounts:
for account in accounts[service]:
account.setupAccount(account['username'], account['password'])
But as you may have guessed it didn't work, Python returns:
TypeError: 'MailAccount' object is not subscriptable
If i create the same account manually however it works:
account = MailAccount()
account.setupAccount('myusername', 'mypassword')
Now i believe it has something to do with the fact that my <MailAccount Object at xxxx>
is a dictionary key right? That makes it non-subscriptable (whatever that may mean)?
No what exactly does this mean to be non-subscriptable? What does it imply in this example? And of course: how can i solve / bypass this in this case?
Thanks,
Benjamin :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决这个问题的方法是正确使用词典。
The way to fix it is to use dictionaries properly.
问题是,当您迭代字典时,您获得的是该字典的键,而不是项目。
如果您想迭代这些值,请执行以下操作:
还有一个
items
方法,可同时用于键和值:The problem is that when you iterate over a dictionary, you get the keys of that dictionary, not the items.
If you want to iterate over the values, do this:
There is also an
items
method, for both keys and values at the same time: