TypeError:' collections.defaultdict'对象不可调用

时间:2017-09-11 03:35:09

标签: python python-2.7

当我尝试在索引中打印对象时出现此错误..我要做的是搜索lname并打印其对象值...

from collections import defaultdict
class Pbook(object):
    lname_index = defaultdict(list)

    def __init__(self, lname, fname, age):
        self.lname=lname
        self.fname=fname
        self.age=age
        Pbook.lname_index[lname].append(self)

    def __str__(self):
        return "%s %s %s" % (self.lname, self.fname, self.age)



myList = []
myList.append(Pbook("john","smith",23))
myList.append(Pbook("george","bush",25))

print Pbook.lname_index
  

defaultdict(,{' bush':[< main .Pbook对象at   0x000000000585EC50>],'史密斯':[< 主要 .Pbook对象at   0x000000000585EC88>]})

if "bush" in Pbook.lname_index:
    print "found"

发现

if "bush" in Pbook.lname_index:
    print Pbook.lname_index(myList)
  

TypeError:' collections.defaultdict'对象不可调用

1 个答案:

答案 0 :(得分:0)

  1. myList的数据类型为list。这永远不能用作字典的键。 Thumb规则是键应该是可清除的,因此我们使用stringnumberstuples的字典键,它们都是immutable

  2. 正如dict指出的那样,应该使用[]或使用.get()来访问。

  3. 示例代码

    from collections import defaultdict
    class Pbook(object):
        lname_index = defaultdict(list)
    
        def __init__(self, lname, fname, age):
            self.lname=lname
            self.fname=fname
            self.age=age
            Pbook.lname_index[lname].append(self)
    
        def __str__(self):
            return "%s %s %s" % (self.lname, self.fname, self.age)
    
    
    
    myList = []
    myList.append(Pbook("john","smith",23))
    myList.append(Pbook("george","bush",25))
    
    print Pbook.lname_index.get("john")
    print Pbook.lname_index.get("george")
    print Pbook.lname_index.get("bush", None)