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

前端 未结 3 913
花落未央
花落未央 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条回答
  •  醉话见心
    2020-12-09 16:34

    I don't think there's a standard method to do it, but if you need it often, you can just put together your own small function:

    import functools
    import collections
    
    
    def partialclass(cls, *args, **kwds):
    
        class NewCls(cls):
            __init__ = functools.partialmethod(cls.__init__, *args, **kwds)
    
        return NewCls
    
    
    if __name__ == '__main__':
        Config = partialclass(collections.defaultdict, list)
        assert isinstance(Config(), Config)
    

提交回复
热议问题