The default factory of collections.defaultdict
(any callable) does not accept arguments.
If default_factory is not None, it is called without arguments to
provide a default value for the given key, this value is inserted in
the dictionary for the key, and returned.
In other words, defaultdict
does not pass any information to the default_factory
.
Subclass defaultdict
to customize the default __missing__
hook to call the default_factory
(Room
class constructor) with missing key as a parameter:
from collections import defaultdict
class mydefaultdict(defaultdict):
def __missing__(self, key):
self[key] = new = self.default_factory(key)
return new
The constructor of Room
will then look like
class Room(object):
def __init__(self, identity):
self.numbers = []
self.identify = identity
You'll need to use mydefaultdict
instead of defaultdict
from now on. Example:
room = mydefaultdict(Room)
print(room['Train'].getRoom()) # Train
print(room['Hospital'].getRoom()) # Hospital
While this works, I suggest you to re-think the way you store/access data.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…