Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中同时为对象分配多个属性_Python_Class_Attributes_Tuples - Fatal编程技术网

在Python中同时为对象分配多个属性

在Python中同时为对象分配多个属性,python,class,attributes,tuples,Python,Class,Attributes,Tuples,我有一个函数 def foo(a): first_thing = 'first' + a second_foo = 'second' + a + 'bar' return first_thing, second_foo 返回元组。 我怎样才能达到这样的目标 class Thing(object): def __init__(self, a): first_thing, second_foo = foo(a) self.first

我有一个函数

def foo(a):
    first_thing = 'first' + a
    second_foo =  'second' + a + 'bar'
    return first_thing, second_foo
返回元组。 我怎样才能达到这样的目标

class Thing(object):
    def __init__(self, a):
        first_thing, second_foo = foo(a)
        self.first_thing = first_thing
        self.second_foo = second_foo
以更好、更自动化的方式

我尝试了:

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

但是无法正确解包。

您的函数返回值的元组(2元组),而不是2元组的iterable。您正在迭代包含字符串的元组,并且无法将返回的字符串解包为两个

您可以坚持使用原始解决方案,也可以将项目直接解压缩到实例属性中:

self.first_thing, self.second_foo = foo(a)
_ATTR_NAMES = ('first_thing', 'second_foo')

class Thing(object)
    def __init__(self, a):
        for key, value in zip(_ATTR_NAMES, foo(a)):
            setattr(self, key, value)
对于许多属性:

self.first_thing, self.second_foo = foo(a)
_ATTR_NAMES = ('first_thing', 'second_foo')

class Thing(object)
    def __init__(self, a):
        for key, value in zip(_ATTR_NAMES, foo(a)):
            setattr(self, key, value)
为什么不只是:

class Thing(object):
    def __init__(self, a):
        self.first_thing, self.second_foo = foo(a)
您不需要
\uuuu init\uuuu()
函数中的第一行

根据您的评论,您可以在
foo
函数中返回字典,并使用
setattr()
,更新后的解决方案是:

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


class Thing(object):
    def __init__(self, a):
        for k, v in foo(a).items():
            setattr(self, k, v)

如果函数返回不同数量的参数,则可以从
foo
返回字典,并更新
\uuu dict\uu
属性

def foo(a):
    return {'first' : 'first' + a, 'second' : 'second' +  a + 'bar'}

class Thing(object):
    def __init__(self, a):
        self.__dict__.update(foo(a))


请注意这种方法的注意事项,最重要的是对更新内容缺乏控制

self.first\u thing,self.second\u foo=foo(a)
?是否返回未知数量的参数?但这意味着我需要手动指定所有值。这难道不能做得更好一点吗,比如java反射,它将采用文字名称,即
first\u thing
,并将
first\u thing
存储为属性及其相应的值,你需要在
foo
函数中返回一个字典而不是元组。你推荐
self.\uu dict\uuuu.update(foo(a))
还是
setattr(self,k,v)
?我个人推荐
setattr()
,因为它更安全。你可以在这个答案中找到一些细节