Python:在子类中使用父类的字典

时间:2013-10-29 23:47:09

标签: python class inheritance subclass

我想使用父类“Graph”中的字典,并在名为“Summary”的子类中使用它。

字典是节点,度,邻居,直方图和图形。

尝试使用“graph。(Tab completion)”时,无法使用Summary中的函数,因此这就是我遇到的问题。

我是python和编程的新手,所以我不知道我想要做的是否可能。

class Graph:
    '''docstring'''

    def __init__(self, graph):

        d = {}
        d1 = {}
        d2 ={}
        with myfile as f:
            next(f)
            for line in f:
                k, v = line.split()
                d[int(k)] = int(v)
                next(f)

            myfile.seek(0)

            data = [line.strip() for line in myfile]
            d1 = dict(enumerate(data))

            del d1[0]

            d2 = {key: list(map(int, value.split())) for key, value in d1.items()}

            i = 1
            while i <= max(d2.keys()):
                del d2[i]
                i += 2

            neighbors = dict(enumerate(d2.values(), start = 1))


        hist = defaultdict(list)
        for key, values in neighbors.iteritems():
            hist[len(values)].append(key)
        histogram = dict(hist)

        degree = d.values()
        nodes = d.keys()

        self.graph = graph
        self.nodes = nodes
        self.degree = degree
        self.neighbors = neighbors
        self.histogram = histogram

class Summary(Graph):
    def __init__(self, graph):
        Graph.__init__(self, graph)

    def Avg_Connectivity(self):


        return ("Average Node Connectivity:", np.average(self.degree))

    def Max_Connectivity(self):

        return ("Maximum Node Connectivity:" , max(self.degree)),("Node with Maximum Connectivity:", self.nodes[self.degree.index(max(self.degree))]) 

    def Min_Connectivity(self):
        return ("Minimum Node Connectivity:", min(x for x in self.histogram.keys() if x != 0)),("Nodes with Minimum Connectivity", self.histogram[min(x for x in self.histogram.keys() if x != 0)])


if __name__ == '__main__':

    import numpy as np
    from collections import defaultdict
    infile = raw_input("Enter File Name (e.g. e06.gal): ")
    myfile = open(infile, 'r')
    graph = Graph(myfile)

2 个答案:

答案 0 :(得分:0)

通常,Summary会继承Graph中的所有字段和方法。因此,您可以访问self.graph中的self.nodesSummary。您是否尝试访问这些字段?如果它不起作用,那是什么错误?

答案 1 :(得分:0)

根据评论,您没有在任何地方使用Summary。你有一个Graph对象。子类将“新方法”“添加”到现有类,但它们仅存在于 new 类中,而不是您继承的类。

无论如何,继承对这个问题来说是一个糟糕的选择; “摘要”不是“图”的特例。您需要一个包装图形的单独对象。

class Summary(object):
    def __init__(self, graph):
        self.graph = graph

    def avg_connectivity(self):
        return ("Average Node Connectivity:", np.average(self.graph.degree))

    # ... etc


if __name__ == '__main__':
    import numpy as np
    infile = raw_input("Enter File Name (e.g. e06.gal): ")
    myfile = open(infile, 'r')
    graph = Graph(myfile)
    summary = Summary(graph)

调整其他方法以直接使用self.graph而非self上的属性。现在summary将拥有您想要的方法。

您的代码的其他一些评论:

  • 你有非常非常长的台词。您可以在括号中的任何位置换行,或者使用临时变量而不是相同的长表达式两次。

  • Foo_Bar是一种非常不寻常的名字造型方式;保持小写。

  • 您的Graph构造函数采用一个打开的文件(容易引起注释graph),然后将其保留为self.graph。你可能不需要这样做。

  • 您的变量名称通常很难理解:d vs d1 vs d2hist vs histogram。评论也会有所帮助。

  • 您应该将import放在文件的顶部,而不是放在底部的此块中。

  • 此文件格式是否有成对的行?阅读有点复杂;我同情:)