您的基本问题是使用类代替函数。没有将该类绑定到调用它的实例的机制,这与自动执行该函数的函数不同。
简而言之,当您执行
a.foo( .. )此操作时,它会返回
MultiMethod,但该对象并不知道应该绑定到
a。
您必须以某种方式传递实例。一种简单的方法是将所有内容包装在一个函数中,然后让Python完成操作:
registry = {}class MultiMethod(object): def __init__(self, name): self.name = name self.typemap = {} # self = a MultiMethod instance, instance = the object we want to bind to def __call__(self, instance, *args): types = tuple(arg.__class__ for arg in args) # a generator expression! function = self.typemap.get(types) if function is None: raise TypeError("no match") return function(instance, *args) def register(self, types, function): if types in self.typemap: raise TypeError("duplicate registration") self.typemap[types] = functiondef multimethod(function): name = function.__name__ mm = registry.get(name) if mm is None: mm = registry[name] = MultiMethod(name) types = tuple(function.__annotations__.values()) mm.register(types, function) # return a function instead of a object - Python binds this automatically def getter(instance, *args, **kwargs): return mm(instance, *args, **kwargs) return getterclass A: @multimethod def foo(self, a: int): return "an int", aa = A() print( a.foo( 1 ) )更复杂的方法是在
A执行此绑定的类上编写自己的描述符。



