简体   繁体   中英

Python: save class object in dictionary

I'm trying to save an class object into dictionary

I've something like this

class Thing:

    def __init__(self, symbol, age, pos):

        worldMap = {}

        self.symbol = symbol
        self.age = age
        self.pos = pos


t1 = Thing('c', 2, '')
t2 = ..

t1.worldMap

When I try to add t1 to the worldMap it doesn't work. What am I missing here?

save an class object into dictionary, so i can use it in an array.

This doesn't make any sense.

Any way, in order to save an object as a key in a dictionary you will need to override the __hash__ method. It should return the hash of its members (those that will be unique to each instance of the class).

The worldmap is an attribute of your instance t1, adding the instance to itself is not what you want I guess.

You either have to create a global variable world map holding all the Class-Instances or make it static. You should rather go for the first approach though, else your Thing-Class will hold the reference to itself again.

Didn't quite get what you are trying to achieve, but it looks like the problem is you just using new dict every time. If that is the case, then you just need to save the dict somewhere:

class Thing:
    def __init__(self, symbol, *args, **kwargs):
        # get existing dict, or create it for the first run
        worldMap = getattr(self.__class__, 'worldMap', {})
        worldMap.update(symbol, self)

        # save the dict to use it later
        self.__class__.worldMap = worldMap

t1 = Thing('c', 1, 2)
assert(t1.worldMap['c'] == t1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM