我有一组类,它们的属性之一是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.
如果要将此类实例化为我想要的字典,我该怎么办?
答案 0 :(得分:3)
class pagesByUrl(dict):
"a cross reference of pages by url rather than object name"
def __init__(self):
dict.__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
self.update(pages)
#Alternatively, forgo the previous `dict.__init__(self)` and the
#previous line and do:
#dict.__init__(self,pages)
如果您执行self = pages
,则只需使用self
字典替换__init__
函数中的本地名称pages
即可。你实际上并没有改变self
的字典。
当然,此时,根本不需要pages
字典 - 我们可以使用self
:
class pagesByUrl(dict):
"a cross reference of pages by url rather than object name"
def __init__(self):
dict.__init__(self)
for page in dir(xxxPages):
try:
pgAttr=getattr(xxxPages, page)
pg=pgAttr('dummybrowser')
self[pg.url] = page
except (KeyError, TypeError, AttributeError):
pass
答案 1 :(得分:0)
如果你想拥有纯粹的“类型字典”,请查看实例创建的__new__()
方法
class dictA(dict):
def __new__(self):
self._pages={"one":1, "two":2}
return self._pages
class pagesByUrl(dict):
def __init__(self):
_pages = {"one":1, "two":2}
dict.__init__(self)
self.update(_pages)
d = {"one":1, "two":2}
print type(d)
print d
d = dictA()
print type(d)
print d
d = pagesByUrl()
print type(d)
print d
输出:
<type 'dict'>
{'two': 2, 'one': 1}
<type 'dict'>
{'two': 2, 'one': 1}
<class '__main__.pagesByUrl'>
{'two': 2, 'one': 1}