1

I have a set of classes that have as one of their attributes a url. I would like to build a dictionary of those classes, keyed by that url. Here is the code I have come up with:

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.  

What can I do to have this class instantiate as the dictionary that I want?

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__()純粋な「type dict」が必要な場合は、インスタンス作成の方法を 確認してください

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 に答える