Pythonic way to assign the parameter into attribute?
class, methods, oop, python
Solution
you can do something like:
def assign(self,**kwargs):
for k,v in kwargs.items():
if v:
setattr(self,k,v)
This is quite simple and suitable for many situations. If you want to maintain a set of keywords which you'll accept and raise TypeError for the rest:
#python2.7 and newer
def assign(self,allowed_kwargs={'foo','bar','baz'},**kwargs):
if kwargs.keysview() - allowed_kwargs:
raise TypeError('useful message here...')
for k in allowed_kwargs:
setattr(self,k,kwargs[k])
This is somewhat inspect-able as well since the user will see the set of allowed kwargs.
Problem
The sample codes are like this: ``` def assign(self, input=None, output=None, param=None, p1=None, p2=None): if input: self.input = input if output: self.output = output if param: self.param = param if p1: self.p1 = p1 if p2: self.p2 = p2 ``` Though this looks very clear, it suffers if there're 10 parameters for this function. Does anyone have ideas about a more convinient way for this?