Eva*_*enn 12 python partial functools
我想创建一个行为类似collections.defaultdict的类,而没有使用代码指定工厂.EG:而不是
class Config(collections.defaultdict):
pass
Run Code Online (Sandbox Code Playgroud)
这个:
Config = functools.partial(collections.defaultdict, list)
Run Code Online (Sandbox Code Playgroud)
这几乎可行,但是
isinstance(Config(), Config)
Run Code Online (Sandbox Code Playgroud)
失败.我打赌这个线索意味着还有更深层次的狡猾问题.那么有没有办法真正实现这一目标?
我也尝试过:
class Config(Object):
__init__ = functools.partial(collections.defaultdict, list)
Run Code Online (Sandbox Code Playgroud)
小智 22
至少在 Python 3.8.5 中它只适用于functools.partial:
import functools
class Test:
def __init__(self, foo):
self.foo = foo
PartialClass = functools.partial(Test, 1)
instance = PartialClass()
instance.foo
Run Code Online (Sandbox Code Playgroud)
fja*_*rri 10
我不认为有一种标准方法可以做到这一点,但如果你经常需要它,你可以把你自己的小功能组合在一起:
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)
Run Code Online (Sandbox Code Playgroud)
小智 9
我有一个类似的问题,但也要求我的部分应用类的实例是可腌制的。我想我会分享我最终的结果。
我通过查看 Python 自己的collections.namedtuple. 下面的函数创建了一个可以腌制的命名子类。
from functools import partialmethod
import sys
def partialclass(name, cls, *args, **kwds):
new_cls = type(name, (cls,), {
'__init__': partialmethod(cls.__init__, *args, **kwds)
})
# The following is copied nearly ad verbatim from `namedtuple's` source.
"""
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in enviroments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython).
"""
try:
new_cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return new_cls
Run Code Online (Sandbox Code Playgroud)
如果您确实需要通过 进行显式类型检查isinstance,您可以简单地创建一个不太简单的子类:
class Config(collections.defaultdict):
def __init__(self): # no arguments here
# call the defaultdict init with the list factory
super(Config, self).__init__(list)
Run Code Online (Sandbox Code Playgroud)
您将使用列表工厂进行无参数构造,并且
isinstance(Config(), Config)
Run Code Online (Sandbox Code Playgroud)
也会起作用。