Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to assign the parameter into attribute?

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?

like image 568
Hanfei Sun Avatar asked Mar 10 '13 02:03

Hanfei Sun


People also ask

How do you pass parameters in Python?

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.

How do you modify attributes in Python?

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.

What is __ dict __ in Python?

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__.


1 Answers

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.

like image 183
mgilson Avatar answered Sep 27 '22 21:09

mgilson