Code: Alles auswählen
# -*- coding: utf-8 -*-
class Collection(object):
def __init__(self):
self.functions = {}
def __call__(self, description, output="{0}"):
def wrapper(function):
name = function.func_name
varnames = function.func_code.co_varnames
argcount = function.func_code.co_argcount
args = varnames[:argcount]
self.functions[name] = (function, description, output, args)
return function
return wrapper
def __getitem__(self, name):
return self.functions[name]
collection = Collection()
@collection("multiplies {1} with {2}", "{1}*{2}={0}")
def mul(a, b):
return a * b
@collection("squares {1}")
def square(a):
return a**2
def main():
while True:
name = raw_input("function:")
function, description, output, args = collection[name]
print '"%s" %s:' % (name, description.format(name, *args))
params = [float(raw_input(" %s=" % arg)) for arg in args]
x = function(*params)
print output.format(x, *params)
if __name__ == "__main__":
main()
Code: Alles auswählen
function:mul
"mul" multiplies a with b:
a=2
b=3
2.0*3.0=6.0
function:square
"square" squares a:
a=4
16.0
function:
Ich hätte auch noch eine Lösung mit Metaklassen, aber die war nicht so flexibel (man konnte jede Funktion nur einer Sammlung hinzufügen und war an Klassen gebunden).
Sebastian