使用key作为参数的defaultdict创建类对象时触发TypeError问题求助
问题解决:defaultdict使用key初始化实例的TypeError错误
错误原因
你定义的lambda表达式要求传入xy参数,但defaultdict在生成默认值时,不会给工厂函数传递任何参数,因此调用lambda时缺少必要参数,触发TypeError。
解决方案
要实现用访问的key来初始化Intersection实例,需要自定义defaultdict的子类,重写__missing__方法,让它将当前访问的key传递给默认工厂函数:
from collections import defaultdict from typing import Tuple class Intersection: def __init__(self, xy: Tuple[int, int]): self.position = xy self.stuff = [] def add(self, stuff): self.stuff.append(stuff) class KeyDefaultDict(defaultdict): def __missing__(self, key): # 用当前key创建实例并赋值 self[key] = self.default_factory(key) return self[key] # 直接将Intersection作为默认工厂函数 intersections: KeyDefaultDict[Tuple[int, int], Intersection] = KeyDefaultDict(Intersection) intersections[(1,2)].add('stuff') # 验证结果 print(intersections[(1,2)].position) # 输出: (1, 2)
补充说明
defaultdict的默认行为是:当访问不存在的key时,调用工厂函数无参创建值。如果需要用key参与值的初始化,必须通过重写__missing__方法来实现,因为这个方法会接收当前访问的key作为参数。
内容的提问来源于stack exchange,提问作者Chris Rudd
相关产品推荐
相关产品推荐

