[Tutor] Difference between decorator and inheritance
bob gailer
bgailer at gmail.com
Fri Aug 2 11:26:10 EDT 2019
And now for something completely different...
Decorators are not required to return a function!
I use them to create a dictionary that maps function names to the
corresponding function object.
This is very useful when associating actions with user-entered commands.
Example:
def collect(func=None, d={}):
if not func: return d
d[func.__name__] = func
@collect
def add(a,b):
return a+b
# adds item to dictionary d (key = 'add', value = func)
# repeat for other user-command functions
# finally:
cmd_dict = collect() # returns the dictionary
cmd = input('enter a command>')
func = cmd_dict.get(cmd)
--
Bob Gailer
More information about the Tutor
mailing list