Python类无法在main中初始化,错误的参数使用?

时间:2017-10-16 06:52:59

标签: python class parameters

我很确定我错误地初始化了列表,但无论是错误的参数还是未对齐的语法我都说不出来。 起初,我认为这是由于类在main()中不可见,但在删除main之后,仍然返回相同的错误。 我已阅读Python参考资料,发现我们的代码之间没有差异。非常欣赏任何看不见的错误。提前谢谢!

参考:https://docs.python.org/3/tutorial/classes.html

错误返回:

Traceback (most recent call last):
File "dfs_final.py", line 12, in <module>
class node(object):
File "dfs_final.py", line 77, in node
main()
File "dfs_final.py", line 68, in main
nodes = [ node(i, nodes[2*i], nodes[(2*i)+1, false] ) for i in range(10)]
File "dfs_final.py", line 68, in <listcomp>
nodes = [ node(i, nodes[2*i], nodes[(2*i)+1, false] ) for i in range(10)]
NameError: name 'node' is not defined

代码:

class node(object):

  def __init__(self,cargo = None, left = None, right = None, found = None):
    self.cargo = cargo
    self.left = left
    self.right = right
    self.found = found

 def __str__(self):
   return str(self.cargo)

# pass in root to begin search
def DFS(curr_node, visited = []):

# Return if node DNE
if not curr_node:
  return


# if already visited, return cycle

for i in visited:
  if (curr_node.cargo == visited[i]):
    err_str = "It's a cycle :("
    return err_str

# mark node as found
curr_node.found = true

# add to visited list
visited += [curr_node.cargo]


# pass in node.left, node.right to recurse

DFS(curr_node.left, visited) # Go left first
DFS(curr_node.right, visited) # Try right

# After finished traversing tree
return visited

def main():

  adjacency_matrix = {1: [2, 3], 2: [4, 5],
    3: [5], 4: [6], 5: [6],
    6: [7], 7: []}

  # Initialize array of nodes to pass
  for i in range(10):
    nodes = [ node(i, nodes[2*i], nodes[(2*i)+1, false] ) for i in range(10)]

  for i in nodes:
    print(nodes[i].cargo)

  # Pass into function
  # DFS(nodes)

if __name__ == "__main__":
main()

2 个答案:

答案 0 :(得分:1)

  for i in range(10):
      nodes = [ node(i, nodes[2*i], nodes[(2*i)+1, false] ) for i in range(10)]

在构建列表时,您无法在列表推导中引用nodes。 (即使你可以尝试访问尚未初始化的元素)。

答案 1 :(得分:0)

Python使用缩进。 Python不使用括号来分隔函数体,因此缩进需要正确。

这是一段简单的代码:

if True:
    print("Hello")

现在这里有一段错误的代码:

if True:
print("Hello")

这会出现错误。 Python如何知道函数的结束位置?或if声明?

现在,假设这只是一个复制粘贴问题,您的代码中会出现问题。

for i in range(10):
    nodes = [ node(i, nodes[2*i], nodes[(2*i)+1, false] ) for i in range(10)]

你试图在这里做两次同样的事情。使用

nodes = [ node(i, nodes[2*i], nodes[(2*i)+1, false] ) for i in range(10)]

nodes = []
for i in range(10):
    nodes.push( node(i, nodes[2*i], nodes[(2*i)+1, false]) )

此外,您在)之后的这一行中交换了]false

nodes = [ node(i, nodes[2*i], nodes[(2*i)+1, false] ) for i in range(10)]

这不是您代码中的唯一错误,但这是您刚刚报告的错误的解决方案。