class - Assigning multiple attributes to an object at once in Python -


i have function

def foo(a):     first_thing = 'first' +     second_foo =  'second' + + 'bar'     return first_thing, second_foo 

which returns tuples. how can achieve like

class thing(object):     def __init__(self, a):         first_thing, second_foo = foo(a)         self.first_thing = first_thing         self.second_foo = second_foo 

in nicer , more automated fashion?

i experimented with:

def __init__(self, a):         key, value in foo(a):             setattr(self, key, value) 

but can't unpack correctly.

why not just:

class thing(object):     def __init__(self, a):         self.first_thing, self.second_foo = foo(a) 

you not need first line inside __init__() function.

as per comment, can return dictionary in foo function , use setattr(), updated solution be:

def foo(a):     first_thing = 'first' +     second_foo =  'second' + + 'bar'     return {'first_thing': first_thing, 'second_foo': second_foo}   class thing(object):     def __init__(self, a):         k, v in foo(a).items():             setattr(self, k, v) 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -