我有那个代码:
class Welcome(object): MyHouse='Earth' def say(self, what): print(what, self.MyHouse) welcome = Welcome() Living = ['World', 'Planet', welcome.MyHouse] MyChoice = list(map(lambda choice : setattr(welcome, 'MyHouse', choice), Living)) print(''.join(str(MyChoice) for MyChoice in MyChoice)) getattr(welcome, 'say')('Hello')
有了这个代码,我想使用setattr()来改变MyHouse变量根据包含在生活列表中的字符串,但当我看到的结果我只得到无对象?,为什么这和我如何修复它,这将是因为setattr不给输出?。
print(MyChoice) Output: [None, None, None]
因此,在我设法解决了一杯咖啡之后,我只需要使用一个for循环,尽管我不知道它起作用的确切原因,并且希望得到一个解释,我只是认为map()将消除对for循环的需要。代码如下:
class Welcome(object): MyHouse='Earth' def say(self, what): print(what, self.MyHouse) welcome = Welcome() Living = ['World', 'Planet', welcome.MyHouse] MyChoice = map(lambda choice : setattr(welcome, 'MyHouse', choice), Living) for i in MyChoice: getattr(welcome, 'say')('Hello')
这是一个无用的代码,如果我需要一个for循环,为什么我使用lambda和map。