How to pickle and unpickle instances of a class that inherits from defaultdict?

后端 未结 2 1322
一向
一向 2020-12-16 19:28

I have a class that inherits from defaultdict like this:

class listdict(defaultdict):
    def __init__(self):
        defaultdict.__init__(self,         


        
2条回答
  •  我在风中等你
    2020-12-16 20:01

    That error indicates that your 'listdict' class was expected to take one argument (the implicit self), but got two arguments.

    Your class inherits from defaultdict, and defines an initializer. This initializer calls defaultdict's initializer and passes 'list' to it, which in this case may be either a function or a class. (I can't be bothered to check).

    What you probably meant is to do this:

    class listdict(defaultdict):
        def __init__(self, list):
            defaultdict.__init__(self, list)
    

    Now, when listdict is initialised with a given list, it passes THAT list to the defaultdict's constructor, rather than passing a reference to the global list.

    (That said, it's considered bad style to use a name that is the same as common global methods and classes, such as 'str', 'list', etc, for the same reason that you got confused).

提交回复
热议问题