简体   繁体   English

Python如何在两个def之间传递变量

[英]Python how to pass variable between two def

I would pass a variable between two def inside a function. 我会在函数内部的两个def之间传递变量。 How can i do? 我能怎么做? i tried using global but didn't work 我尝试使用全局但没有用

class example:

 def funz1(self,q,b):
    global queue
    queue = []
    queue += [q]
    queue += [a]

 def funz2(self):
    return str(queue.pop())

but it said me that queue is an empty list 但它说我队列是空列表

You have to use the self parameter, which points to the example instance itself: 您必须使用self参数,该参数指向example实例本身:

class example:    
 def funz1(self,q,b):
    self.queue = []
    self.queue += [q]
    self.queue += [a]

 def funz2(self):
    return str(self.queue.pop())

Read more here . 在这里阅读更多。

Also, as a side note, array += [item] is wrong, you should use array.append(item) 另外,请注意, array += [item]是错误的,您应该使用array.append(item)

There are several issued with that code, first, there is no need to use a global bar since you can access self. 该代码有多个发行版,首先,由于您可以访问self,因此无需使用全局栏。 Also, pop will raise an exception if the list is not empty, therefore, you can have the following: 另外,如果列表不为空,pop将引发异常,因此,您可以具有以下内容:

class example:    
    def __init__(self):
        self.queue = []

    def funz1(self,q,b):
        self.queue.append(q)
        self.queue.append(b)

    def funz2(self):
        if len(self.queue) > 0:
            return str(self.queue.pop())

On top of that, if you are using a list as aq you might as well use deque from collections which was designed for that use: 最重要的是,如果您使用列表作为aq,则最好使用为此目的设计的集合中的双端队列:

from collections import deque

class example:    
    def __init__(self):
        self.queue = deque()

    def funz1(self,q,b):
        self.queue.append(q)
        self.queue.append(b)

    def funz2(self):
        if len(self.queue) > 0:
            return str(self.queue.popleft())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM