0

我想使用字典访问我的用户类的所有实例。
我启动(正确的词?)像这样的实例,save_dat作为字典。

for a in save_dat:
    a = user(a,save_dat[a])
    a.some_method

效果很好。
但是,稍后我想再次访问这些实例。我的想法:

for a in save_dat:
    a.some_method

不起作用,error: 'str' object has no attribute 'name' 但我已经在save_dat用户实例中输入了这些条目!?
我真的不能a = user(a,save_dat[a])再这样做了,因为这会覆盖其中一些实例的更改属性(我认为..),它们应该已经是用户实例?!

4

2 回答 2

0

试试这个(假设它user是一个返回实例的函数,或者是一个以小写字母开头的类的名称):

users = {}
for a, data in save_dat.items():
    users[a] = user(a, data)
    users[a].some_method ()

然后:

for a in users.values():
    a.some_method ()

如果你真的想更新你的字典而不是创建一个新字典users,试试这个:

save_dat = {key: user(key, value) for key, value in save_dat.items() }

接着:

for a in save_dat.values():
    a.some_method ()
于 2013-09-08T07:51:13.090 回答
0

What I could understand is that with a = user(a,save_dat[a]) you are trying to save the instances in the save_dat dictionary.

But doing a = user(a,save_dat[a]) wouldn't work how you want it. For example:

some_dict = { 1: 3, 2: 4}
for i in some_dict:
    i = 5

This doesn't change the dictionary to { 1: 5, 2: 5}, rather the dictionary doesn't change at all.

For changing the dictionary we have to do something like this:

some_dict = { 1: 3, 2:4}
for i in some_dict:
    some_dict[i] = 5

So, what you should do is:

for a in save_dat:
    save_dat[a] = user(a,save_dat[a])
    save_dat[a].some_method
于 2013-09-08T07:59:56.063 回答