我有一组类,它们的属性之一是 url。我想构建一个由该 url 键入的类的字典。这是我想出的代码:
class pagesByUrl(dict):
"a cross reference of pages by url rather than object name"
def __init__(self):
pages={}
for page in dir(xxxPages):
try:
pgAttr=getattr(xxxPages, page)
pg=pgAttr('dummybrowser')
pages[pg.url] = page
except (KeyError, TypeError, AttributeError):
pass
print pages #At this point, the dictionary is good.
self=pages
print self #Also here, still just what I want.
pg=pagesByUrl()
print "pg is:", pg #But here, pg is an empty dictionary.
我该怎么做才能让这个类实例化为我想要的字典?