从另一个函数调用在一个函数内部定义的变量

发布于 2021-01-29 14:55:27

如果我有这个:

def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])

def anotherFunction():
    for letter in word:              #problem is here
        print("_",end=" ")

我之前已定义lists,因此oneFunction(lists)效果很好。

我的问题是word在第6行中调用。我试图word用相同的word=random.choice(lists[category])定义在第一个函数之外进行定义,但是word即使调用,它也始终相同oneFunction(lists)

我希望每次调用第一个函数然后再调用第二个函数时,都具有一个不同的word

我能做到这一点,而不界定wordoneFunction(lists)

关注者
0
被浏览
161
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    是的,您应该考虑在一个类中定义您的函数,并使word成为成员。这比较干净

    class Spam:
        def oneFunction(self,lists):
            category=random.choice(list(lists.keys()))
            self.word=random.choice(lists[category])
    
        def anotherFunction(self):
            for letter in self.word:              
            print("_",end=" ")
    

    创建类后,您必须将其实例化为对象并访问成员函数。

    s = Spam()
    s.oneFunction(lists)
    s.anotherFunction()
    

    另一种方法是使oneFunction单词返回,以便您可以使用oneFunction而不是单词inanotherFunction

    >>> def oneFunction(lists):
            category=random.choice(list(lists.keys()))
            return random.choice(lists[category])
    
    
    >>> def anotherFunction():
            for letter in oneFunction(lists):              
            print("_",end=" ")
    

    最后,您还可以使anotherFunction,接受word作为参数,您可以从调用结果中传递该参数oneFunction

    >>> def anotherFunction(words):
            for letter in words:              
            print("_",end=" ")
    >>> anotherFunction(oneFunction(lists))
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看