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?
Functions in Python are created and denoted with the def keyword followed by a function name. For example, greet_customer followed by a set of parentheses () . The parameters of the function are stored in the parentheses.
If you want your method to modify any attribute, you can pass its name as a string. You can then use getattr() and setattr() to get and set the attribute.
The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With