1

我有一组类,它们的属性之一是 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.  

我该怎么做才能让这个类实例化为我想要的字典?

4

2 回答 2

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__pagesself

当然,此时,根本不需要pagesdict ——我们可以使用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
于 2013-04-12T15:05:58.913 回答
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}
于 2013-04-12T15:33:45.277 回答