Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!

like image 833
AKA.e Avatar asked Feb 08 '23 21:02

AKA.e


1 Answers

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.

like image 168
vaultah Avatar answered Feb 15 '23 10:02

vaultah