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

问题描述 投票:0回答:1

当我尝试打印索引中的对象时出现此错误。我想做的是搜索 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(<type 'list'>, {'bush': [<__main__.Pbook object at
> 0x000000000585EC50>], 'smith': [<__main__.Pbook object at
> 0x000000000585EC88>]})

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

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

> TypeError: 'collections.defaultdict' object is not callable
python python-2.7
1个回答
-1
投票
  1. myList 的数据类型为

    list
    。这永远不能用作字典的键。经验法则是键应该是可哈希的,因此我们使用字典键作为
    string
    numbers
    tuples
    ,它们都是
    immutable

  2. 正如 dict 所指出的,应该使用

    []
    或使用
    .get()
    来访问。

示例代码

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)
© www.soinside.com 2019 - 2024. All rights reserved.