开发者

How to add a map as a class field?

I want to add a dictionary that maps an object 开发者_JAVA技巧to a list of objects as an instance variable to a class. What is the idiomatic way to do it in Python? Here's how I've done it:

class MyClass:
    def __init__(self):
        self.myDict = { None : [None] }  


You have already hit upon the idiomatic way to do it!


Personally, I'd do it this way, if you want the option of starting out with a certain number of objects, and you want it clearer what you're desiring.

class MyClass:
    def __init__(self, objlistdict=None):
        "Takes an optional initial dictionary with objects as keys and lists of objects as values"  # docstrings are very useful for documentation
        self.myDict = {} if objlist is None else objlist # sets `self.myDict` to be the initial dict, otherwise makes it an empty one

Note that the objects you use as keys do need to be hashable, and I believe it's recommended to use immutable objects even if the mutable object you're using still has a hash method defined, due to the fact that objects that compare equal are generally supposed to have the same hash, so changing something about the object will change the hash value, and that might cause problems with being unable to access the value for an original key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜