1

I would pass a variable between two def inside a function. 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

fege
  • 547
  • 3
  • 7
  • 19

2 Answers2

4

You have to use the self parameter, which points to the example instance itself:

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)

Community
  • 1
  • 1
Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
1

There are several issued with that code, first, there is no need to use a global bar since you can access self. Also, pop will raise an exception if the list is not empty, therefore, you can have the following:

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 a q you might as well use deque from collections which was designed for that use:

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())
mandel
  • 2,921
  • 3
  • 23
  • 27