Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I found the answer the the problem. It has to do with the renaming of attributes in class-private variables. This can be seen for <a href="http://docs.python.org/3.0/tutorial/classes.html#private-variables" rel="nofollow">python 3 here</a> under Private Variables and for <a href="http://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references" rel="nofollow">python 2 here</a> section 9.6 Private Variables and Class-local References.</p> <p>In the code with the function as a method (the second listing above), the <code>f.__case</code> was renamed to <code>f._switch__case</code>. If every instance of <code>__case</code> is replaced with <code>_switch__case</code> except for the <code>@staticmethod</code> function, the code works as it should. I'm not 100% sure why Python is designed this way, but I'm guessing it has something to do with preserving namespace, but I'm not sure why it is necessary as <code>class</code> has its own namespace.</p> <p>Below is the corrected code:</p> <pre><code>class switch: def __init__(self): self.__case_map = {} def set_case(key,f): self.__case_map[key] = f a = [getattr(self,e) for e in dir(self) if getattr(self,e) is not None and hasattr(getattr(self,e),'_switch__case')] for f in a: cases = getattr(f,'_switch__case') if isinstance(cases,tuple) or isinstance(cases,list): for c in cases: set_case(c,f) else: set_case(cases,f) def match(self,value): try: self.__case_map[value] except KeyError: return self.__case_map['_default'] return self.__case_map[value] @staticmethod def case(comparision): def __assign_case(f): f.__case = comparision return f return __assign_case class b(switch): @switch.case((1,3)) def event_one(self): print('Event handler for 1,3 in b') @switch.case(2) def event_two(self): print('Event handler for 2 in b') @switch.case('_default') def default(self): print('No match was found, using default case') a = b() a.match(1)() a.match(2)() a.match(5)() </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