For my own entertainment, I was wondering how to achieve the following:
functionA = make_fun(['paramA', 'paramB'])
functionB = make_fun(['arg1', 'arg2', 'arg3'])
equivalent to
def functionA(paramA, paramB):
print(paramA)
print(paramB)
def functionB(arg1, arg2, arg3):
print(arg1)
print(arg2)
print(arg3)
This means the following behaviour is required:
functionA(3, paramB=1) # Works
functionA(3, 2, 1) # Fails
functionB(0) # Fails
The focus of the question is on the variable argspec - I comfortable creating the function body using the usual decorator techniques.
For those that are interested, I was playing around with trying to programmatically create classes like the following. Again the difficulty is in generating the __init__
method with programmatic parameters - the rest of the class appears straightforward using a decorator or maybe a metaclass.
class MyClass:
def __init__(self, paramA=None, paramB=None):
self._attr = ['paramA', 'paramB']
for a in self._attr:
self.__setattr__(a, None)
def __str__(self):
return str({k:v for (k,v) in self.__dict__.items() if k in self._attributes})
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…