Adding function_picker.py to demo class with function parameter and any number of arg and kwarg parameters

This commit is contained in:
Donald Calloway 2025-10-08 14:29:04 -07:00
parent 9098da24c0
commit b122a870cf

58
function_picker.py Normal file
View File

@ -0,0 +1,58 @@
'''
Class FunctionPicker takes a function (func) and multiple args or kargs as parameters and returns the
attribute result.
Instantiated FunctionPicker objects apply the function passed as a parameter to args or kargs
'''
class FuncPick:
def __init__(self, func, *args, **kwargs):
self.result = func(*args, **kwargs)
return
def multiply(x, y):
return x*y
def floor_divide(x, y):
assert y !=0, "Division by zero is not allowed"
return x // y
def addition(*args):
return sum(args)
def product_all(*args):
result = 1
for num in args:
result *= num
return result
def product_value(**kwargs): # Multiply each kwarg.value by 10
factor = 10
result = {}
for key, value in kwargs.items():
result[key] = value * factor
return result
# Example FuncPick class instances:
mult = FuncPick(multiply, 3, 4) # (func, *args)
fdiv = FuncPick(floor_divide, 56, 7) # (func, *args)
add = FuncPick(addition, 3, 6, 81, 99) # (func, *args)
product = FuncPick(product_all, 3, 6, 81, 99) # (func, *args)
product_kwvals = FuncPick(product_value, a=5, b=6, c=7, d=8) # (func, *kwargs)
# Print func argument results:
print(mult.result)
print(fdiv.result )
print(add.result)
print(product.result)
print(product_kwvals.result)
# Output:
# 12
# 8
# 189
# 144342
# {'a': 50, 'b': 60, 'c': 70, 'd': 80} # A dictionary