Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>sj26's solution is a good one. Another alternative, if you want to set up a method that can be overloaded with any user-supplied function or with another of the object's methods, is build a custom descriptor. This descriptor can be used as a decorator (analogous to @classmethod or @staticmethod); and it allows you to store a function in an instance's dictionary, and returns it as a method:</p> <pre><code>import types class overloadable(object): def __init__(self, func): self._default_func = func self._name = func.__name__ def __get__(self, obj, type=None): func = obj.__dict__.get(self._name, self._default_func) return types.MethodType(func, obj, type) def __set__(self, obj, value): if hasattr(value, 'im_func'): value = value.im_func obj.__dict__[self._name] = value def __delete__(self, obj): del obj.__dict__[self._name] </code></pre> <p>Now we can just decorate a function with "@overloadable":</p> <pre><code>class SomeClass(object): def doStuff(self, string): print 'do stuff:', string @overloadable def overLoaded(self, arg): print 'default behavior:', arg </code></pre> <p>And it'll just do the right thing when we overload it for a given instance:</p> <pre><code>&gt;&gt;&gt; sc = SomeClass() &gt;&gt;&gt; sc.overLoaded("test string") # Before customization default behavior: test string &gt;&gt;&gt; sc.overLoaded = sc.doStuff # Customize &gt;&gt;&gt; sc.overLoaded("test string") do stuff: test string &gt;&gt;&gt; del sc.overLoaded # Revert to default behavior &gt;&gt;&gt; sc.overLoaded("test string") default behavior: test string </code></pre>
 

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