我是新来的Python和我得到这个错误,但我不确定为什么:为什么名称节点未定义?
NameError: name 'Node' is not defined
class Node:
# initialisation/constructor
def __init__(self):
self.parents = []
self.children = []
self.parentWeights = []
self.nodeWeight = 0.0
# add child to node
def addChild(self, child, weight):
self.children.append(child)
# add parent with weight to node
def addParent(self, parent, weight):
self.parents.append(parent)
self.parentWeights.append(weight)
if not self in parent.children:
parent.addChild(self, weight)
def calculateWeight(self):
weightSum = sum(self.parentWeights)*self.nodeWeight
self.nodeWeight = weightSum
# run main function if not a library
if __name__ == '__main__':
i1 = Node()
i2 = Node()
h1 = Node()
h2 = Node()
o1 = Node()
h1.addParent(i1, 1)
h1.addParent(i2, 1)
h2.addParent(i2, 1)
h2.addParent(i2, 1)
o1.addParent(h1, -1)
o1.addParent(h2, 1)
i1.nodeWeight = 3
i2.nodeWeight = 5
calculateWeight(h1)
calculateWeight(h2)
calculateWeight(o1)
你可以在其自己的类定义中调用'Node'。唯一的问题是缩进。 – Ivo
试试这个:'class C:C()'(在':'后面加一个换行符)。你会得到'NameError:name'C'没有被定义'。 – Bach