when I run this program, it print NameError global name 'viewAll' is not defined
I’ m a C programmer, I didn’t know why.
viewAll(this) is defined in class binTree,
Platform:Python 2.7 in windows 7 64 bit
#!/usr/bin/python
#-*-coding:gbk-*-
class binTree():
def __init__(this, left = None, right = None, data = 0):
if data == 0:
this = None
else:
this.leftNode = left
this.rightNode = right
this.data = data
def viewAll(this):
if this != None:
print this.data,
viewAll(this.leftNode)
viewAll(this.rightNode)
def creatBT():
temp = input('Please input a number, input "0" for end!')
if temp == 0:
return None
else:
tree = binTree()
tree.data = temp
tree.leftNode = creatBT()
tree.rightNode = creatBT()
return tree
if __name__ == "__main__":
root = creatBT()
root.viewAll()
You need to do a Python tutorial — you’re not understanding how the instance object works in Python instance methods.
Your problem is here:
You need to access
viewAllon the instance you want to call it on:I’m not sure what you’re intending to do here:
but all you are actually doing is pointing the name
thisatNonein the scope of that one function call. It doesn’t change anything about the class instance or anything outside the function.So, in
viewAll,will always be
True, becausethisis again the instance you’ve calledviewAllon — it hasn’t been and can’t be set toNone.