简体   繁体   English

Python:在字典中保存类对象

[英]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. 当我尝试将t1添加到worldMap时,它不起作用。 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. 无论如何,为了将对象保存为字典中的键,您需要覆盖__hash__方法。 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. worldmap是实例t1的一个属性,将实例添加到自身并不是我想要的。

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. 你应该选择第一种方法,否则你的Thing-Class将再次引用自己。

Didn't quite get what you are trying to achieve, but it looks like the problem is you just using new dict every time. 没有完全得到你想要实现的东西,但看起来问题是你每次只使用新的dict。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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