Python 3.4 增加了使用静态方法定义函数重载的功能.这基本上是文档中的示例:
from functools import singledispatch
class TestClass(object):
@singledispatch
def test_method(arg, verbose=False):
if verbose:
print("Let me just say,", end=" ")
print(arg)
@test_method.register(int)
def _(arg):
print("Strength in numbers, eh?", end=" ")
print(arg)
@test_method.register(list)
def _(arg):
print("Enumerate this:")
for i, elem in enumerate(arg):
print(i, elem)
if __name__ == '__main__':
TestClass.test_method(55555)
TestClass.test_method([33, 22, 11])
Run Code Online (Sandbox Code Playgroud)
在其最纯粹的形式中,singledispatch实现依赖于第一个用于标识类型的参数,因此将此功能扩展到实例方法变得棘手.
有没有人有任何关于如何使用(或jerry-rig)此功能以使其与实例方法一起使用的建议?
python single-dispatch instance-method python-3.x python-3.4
我相信这一定很简单,但我找不到答案.
我有一个字典,如:
d = {'a': 1, 'b':2}
Run Code Online (Sandbox Code Playgroud)
我想通过点表示法来访问它,例如: d.a
这SimpleNamespace是为此而设计的,但我不能将dict传递给SimpleNamespace构造函数.我收到错误:TypeError: no positional arguments expected
如何从字典初始化SimpleNamespace?