类/构造函数的等效于functools'partial'的python [英] python equivalent of functools 'partial' for a class / constructor

查看:122
本文介绍了类/构造函数的等效于functools'partial'的python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个行为类似于collections.defaultdict的类,而无需使用代码指定工厂.例如: 代替

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

class Config(collections.defaultdict):
    pass

此:

Config = functools.partial(collections.defaultdict, list)

这几乎可行,但是

isinstance(Config(), Config)

失败.我敢打赌,这个线索意味着还存在着更深层次的问题.那么有没有一种方法可以真正实现这一目标呢?

fails. I am betting this clue means there are more devious problems deeper in also. So is there a way to actually achieve this?

我也尝试过:

class Config(Object):
    __init__ = functools.partial(collections.defaultdict, list)

推荐答案

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

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)

这篇关于类/构造函数的等效于functools'partial'的python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆