Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - Defaultdict of a Class - Get index/key of current called instance inside a class

Yep! I know you cannot understand by the title.
Take for example the below code.

class Room(object):
    def __init__(self):
        self.numbers = []
        self.identify = None #for now?
    def getRoom(self):
        #here I need to implement so that, 
        # self.identify is current indent this class is called!
        return self.identify
room = defualtdict(Room)
print room['Train'].getRoom()
print room['Hospital'].getRoom()

Excepted output.

#>>Train
#>>Hospital

Any such feature supported in defaultdict, so that I can do that? Once the class of room 'something' is called, inside the class, I need a code so that, self.room is 'something' which is called!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...