I am just beginning in python and I am getting the following error:
global name 'data' not defined on line# 62
Following is my code:
class PriorityQueue(object):
"""
Max PriorityQueue
Binary heap based implementation
"""
data = []
def __init__(self):
pass
def insert(self,d):
global data
data.append(d)
__siftup()
def extractMax(self):
global data
max = -1
if not len(data) == 0:
max = data[0]
__siftdown()
return max
def __siftup():
global data
index = len(data) - 1
pIndex = (index - 1)/2
while pIndex > 0 and data[pIndex] > data[index]:
data[pIndex], data[index] = data[index], data[pIndex]
index = pIndex
pIndex = (index - 1)/2
def __siftdown():
global data
data[0] = data.pop()
index = 0
while index *2 <= len(data) -1:
minIndex = __getMinIndex(index)
if data[minIndex] > data[index]:
data[minIndex], data[index] = data[index], data[minIndex]
index = minIndex
else:
break
def __getMinIndex(i):
global data
lIndex = i*2 +1
rIndex = lIndex + 1
if rIndex >= len(data) or data[lIndex] > data[rIndex]:
return lIndex
else:
return rIndex
"""Test Script"""
q = PriorityQueue()
q.insert(3)
Should I consider using instance variable instead of global. I have been mostly using Java and recently switched. Can anyone also provide some link for oops concepts in python.
3 Answers 3
When you write:
class MyClass(object):
data = []
data becomes neither an instance variance for objects made via that class, nor a global variable in the module scope, but a class-level (static) variable.
>> instance = MyClass()
>> instance.data
[]
>> instance.data.append(1)
>> instance.data
[1]
>> other_instance = MyClass()
>> other_instance.data
[1]
This is generally not what you want.
The proper way to create instance variables is to assign them in your __init__ constructor.
class PriorityQueue(object):
def __init__(self):
self.data = []
Then, in your other methods, you can reference data as self.data instead of trying to use the global statement. In fact, try to avoid using globals in general.
Comments
Use the instance varible Luke.
Comments
Perhaps you find this helpfull. Especially the LGB-Part and the following chapters.
These two little examples always helped me to clear my confusion.
#!/usr/bin/python
# -*- coding: utf-8 -*-
class A(object):
def __init__(self, a):
self.a = a
def f(self, v):
return self.a + v
class B(A):
def __init__(self, a, b):
A.__init__(self,a)
self.b = b
def f(self, v):
return A.f(self,v)*self.b
if __name__ == '__main__':
b = B(2,3)
print "18",b.f(4)
b.a = 3
print "21",b.f(4)
With the result:
18 18
21 21
[Finished in 0.1s]
And the second one:
n = 1
def A():
n = 2
def B():
print n
B()
def func1():
n = 2
print n
def func2():
global n
n = 2
print n
if __name__ == '__main__':
func1()
func2()
A()
With the result:
1
2
2
[Finished in 0.3s]
dataat class level because it looked like the Java syntax for an instance field, and not because you would have used a static field in Java.__siftup()and__siftdown()as well.