简体   繁体   English

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

[英]Python: Using dictionaries from parent class in subclass

I want to use the dictionaries from the parent class "Graph"and use it in the subclass called "Summary". 我想使用父类“ Graph”中的字典,并在名为“ Summary”的子类中使用它。

The dictionaries are nodes, degree, neighbors, histogram, and graph. 字典是节点,度,邻居,直方图和图。

The functions in Summary cannot be used when trying to use "graph.(tab completion)", so that is the problem I am running into. 尝试使用“ graph。(制表符完成)”时,不能使用“摘要”中的功能,所以这是我遇到的问题。

I am new to python and programming in general, so I don't know if what I am trying to do is possible or not. 我是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)

In general, Summary inherits all fields and methods from Graph . 通常, Summary继承了Graph所有字段和方法。 So you are able to access self.graph or self.nodes in Summary . 因此,您可以在Summary访问self.graphself.nodes Have you tried to access these fields? 您是否尝试过访问这些字段? If it did not work, what was the error? 如果不起作用,那是什么错误?

Per comments, you're not using Summary anywhere. 根据评论,您不会在任何地方使用Summary You have a Graph object. 您有一个Graph对象。 A subclass "adds" new methods to an existing class, but they only exist in the new class, not the one you inherit from. 子类将新方法“添加”到现有类中,但是它们仅存在于类中,而不存在于您继承的新方法中。

Inheritance is a poor choice for this problem anyway; 无论如何,对于这个问题,继承是一个糟糕的选择。 a "summary" is not a special case of a "graph". “摘要”不是“图”的特殊情况。 You want a separate object that wraps a graph. 您需要一个包装图形的单独对象。

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)

Adjust the other methods to use self.graph rather than properties on self directly. 调整其他方法以使用self.graph而不是直接使用self属性。 Now summary will have the methods you want. 现在, summary将具有您想要的方法。

Some other comments on your code: 关于您的代码的其他注释:

  • You have very, very long lines. 您的行非常非常长。 You can wrap anywhere in parentheses, or use temporary variables instead of the same long expression twice. 您可以在括号内的任何位置换行,或者使用临时变量而不是相同的长表达式两次。

  • Foo_Bar is a very unusual way to style a name; Foo_Bar是一种非常不常见的命名样式的方法。 just keep it lowercase. 保持小写即可。

  • Your Graph constructor takes an open file (confusingly named graph ), and then keeps ahold of it as self.graph . 您的Graph构造函数会使用一个打开的文件(易混淆地命名为graph ),然后将其保留为self.graph You probably don't need to do this. 您可能不需要这样做。

  • Your variable names in general are kind of hard to understand: d vs d1 vs d2 , and hist vs histogram . 通常,您的变量名有点难以理解: d vs d1 vs d2hist vs histogram Comments would help too. 评论也会有所帮助。

  • You should put your import at the top of the file, not in this block at the bottom. 您应该将import文件放在文件的顶部,而不是在此块的底部。

  • Does this file format have pairs of lines? 此文件格式是否有成对的行? Reading that is a little complicated; 阅读有点复杂; I sympathize :) 我同情 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM