Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Regarding the inheritance issue: This can be done with a slight change to MultiMethod. (Iterating through self.typemap and checking with <code>issubclass</code>):</p> <pre><code>registry = {} class MultiMethod(object): def __init__(self, name): self.name = name self.typemap = {} def __call__(self, *args): types = tuple(arg.__class__ for arg in args) # a generator expression! for typemap_types in self.typemap: if all(issubclass(arg_type,known_type) for arg_type,known_type in zip(types,typemap_types)): function = self.typemap.get(typemap_types) return function(*args) raise TypeError("no match") def register(self, types, function): if types in self.typemap: raise TypeError("duplicate registration") self.typemap[types] = function def multimethod(*types): def register(function): name = function.__name__ mm = registry.get(name) if mm is None: mm = registry[name] = MultiMethod(name) mm.register(types, function) return mm return register class A(object): pass class B(A): pass class C(object): pass @multimethod(A,A) def foo(arg1,arg2): print 'works' foo(A(),A()) #works foo(A(),B()) #works foo(C(),B()) #raises TypeError </code></pre> <p>Note that <code>self.typemap</code> is a dict, and dicts are unordered. So if you use @multimethod to register two functions, one whose types are subclasses of the other, then the behavior of <code>foo</code> may be undefined. That is, the result would depend on which <code>typemap_types</code> comes up first in the loop <code>for typemap_types in self.typemap</code>. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload