且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类/构造函数的等效于functools'partial'的python

更新时间:2022-05-08 08:51:04

我认为没有标准的方法可以执行此操作,但是如果您经常需要,可以将自己的小函数组合在一起:

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)