在python中传递带有多重继承的参数

时间:2014-01-09 18:02:30

标签: python oop python-3.x

我是python的新手,并且在传递对象参数方面存在一些问题 我有一个Graph类

的文件
class Graph:
   def __init__(self,Name):
      self.Name = Name
      self.Nodes = {}
      self.Edges = {}
   def addEdgeAndNodes(self,sourceName,targetName): ''' code'''
   def getEdgesCount(self):'''code '''
   def getNodesCount(self):''' code '''
#some more code

以及其他文件UpdateGraph类

import Graph
class UpdateGraph(Graph.Graph):
      def __init__(self,Name):
          super().__init__(Name)
      def addUpdateEdgeAndNodes(self,sourceName,targetName,sourceType,targetType,edgeType):
#some more code

并在GraphBuilder文件中:

from Graph import Graph
from UpdateGraph import UpdateGraph
class GraphDFS:
    def __init__(self,graph):
        self.Graph = graph
        self.dfsRes = {}

    def dfs(self):
         #some code
         print("-->"+self.Graph.getNodesCount())

#some code

class GraphBuilder:
      def __init__(self):
          self.Build()

     def Build(self):
          self.Graph = UpdateGraph(self.name)

def main():
    Graph = GraphBuilder(name)
    dfs = GraphDFS(Graph)
     dfs.dfs()

main()

当我尝试运行代码时会引发错误: AttributeError:'GraphBuilder'对象没有属性'getNodesCount' 在行打印(“ - >”+ self.Graph.getNodesCount())

graph是updateGraph类型 如何传递这个变量,它将被Graph Builder函数识别

1 个答案:

答案 0 :(得分:0)

def main():
    Graph = GraphBuilder(name)
    dfs = GraphDFS(Graph)
    dfs.dfs()

您正在将GraphBuilder的对象传递给GraphDFSself.GraphGraphBuilder的实例,您正在此对象上调用getNodesCount,此对象不包含这种方法。

from Graph import Graph
from UpdateGraph import UpdateGraph
class GraphDFS:
    def __init__(self,graph):
        self.Graph = graph
        self.dfsRes = {}

    def dfs(self):
         #some code
         print("-->"+self.Graph.getNodesCount())

#some code

class GraphBuilder:
    def __init__(self, name):
        self.name = name

    def Build(self):
        self.Graph = UpdateGraph(self.name)

def main():
    name = "" # define the name variable
    Graph = GraphBuilder(name)
    Graph.Build()
    dfs = GraphDFS(Graph.Graph)
    dfs.dfs()

main()

将上述代码放在GrapthBuilder文件中,这应该可以正常工作