python equivalent of functools 'partial' for a class / constructor

前端 未结 3 905
花落未央
花落未央 2020-12-09 15:57

I want to create a class that behaves like collections.defaultdict, without having the usage code specify the factory. EG: instead of

class Config(collectio         


        
3条回答
  •  萌比男神i
    2020-12-09 16:41

    If you actually need working explicit type checks via isinstance, you can simply create a not too trivial subclass:

    class Config(collections.defaultdict):
    
        def __init__(self): # no arguments here
            # call the defaultdict init with the list factory
            super(Config, self).__init__(list)
    

    You'll have no-argument construction with the list factory and

    isinstance(Config(), Config)
    

    will work as well.

提交回复
热议问题