2016-02-29 26 views
0

我是Python 2.7的新手,已经从图书馆借用python书籍进行学习,这些书籍可能过于先进,但它们都是他们拥有的。我试图掰开代码想想Compexity由O'Reilly,大约字典辞典如下:了解括号在Python字典中的字典

class Graph(dict): 
    """A Graph is a dictionary of dictionaries. The outer 
    dictionary maps from a vertex to an inner dictionary. 
    The inner dictionary maps from other vertices to edges. 

    For vertices a and b, graph[a][b] maps 
    to the edge that connects a->b, if it exists.""" 

    def __init__(self, vs=[], es=[]): 
     """Creates a new graph. 
     vs: list of vertices; 
     es: list of edges. 
     """ 
     for v in vs: 
      self.add_vertex(v) 

     for e in es: 
      self.add_edge(e) 

    def add_vertex(self, v): 
     """Add a vertex to the graph.""" 
     self[v] = {} 

    def add_edge(self, e): 
     """Adds and edge to the graph by adding an entry in both directions. 

     If there is already an edge connecting these Vertices, the 
     new edge replaces it. 
     """ 
     v, w = e 
     self[v][w] = e 
     self[w][v] = e 

我无法理解什么是括号里面的代码做,如def __init__(self, vs=[], es=[])。我得到它分配属性,“vs”和“es”是列表,但为什么不在函数内部声明?为什么“自我”在那里? def add_vertex(self, v)def add_edge(self, e)也是如此。

无法使用以下函数在函数内声明列表?

vs = {} 
+0

你应该阅读[学习Python](http://shop.oreilly.com/product/0636920028154.do),并学习关于Python的基础知识,特别是参数(第18章 - 涉及你的'vs' /'es问题)和课堂/面向对象(第六部分 - 涉及到你的“自我”问题)。 –

回答

0

vses是初始化Graph类的实例时使用的参数。如果你在__init__里面定义它们,它们在初始化一个实例时总是相同的。 []是用户未传递参数时的默认值。例子:

d1 = Graph(vs=[1,2])    #Creates a graph with 2 vertices, no edges 
d2 = Graph(vs=[1,2,3], es=[(1,3)]) #Creates a graph with 3 vertices, 1 edge 

如果你无法在初始化时指定vses你就必须做到以下几点:

d1 = Graph()   #Creates blank graph 
d1.add_vertex(1)  #Adds vertex 1 
d1.add_vertex(2)  #Adds vertex 2 
d1 == Graph(vs=[1,2]) #Returns True 

d2 = Graph() 
d2.add_vertex(1)  #Adds vertex 1 
d2.add_vertex(2)  #Adds vertex 2 
d2.add_vertex(3)  #Adds vertex 3 
d2.add_edge((1,3)) #Adds edge between vertex 1 and 3 
d2 == Graph(vs=[1,2,3], es=[(1,3)]) #Returns True 
0

self包含在此函数声明和其他像Python未通过self隐含像大多数其他对象的语言,而不是它传递明确,一样的Perl:

def __init__(self, vs=[], es=[]): 

vses只是形式参数的功能,认为它是这样的:

def __init__(self, vs, es): 

=[]部分是默认值,干脆为空表,以保持代码,如果没有提供可选参数断裂。

0

vs=[]es=[]是参数声明默认值。如果在呼叫__init__时忽略它们中的任何一个,它将默认为空列表。 self就是实例本身。你看,__init__不是一个构造函数,而是一个初始化函数;在调用__init__之前构建实例

(名称self是传统的;它可以是this或任何东西收到实例作为他们的第一个参数所有实例方法)。

参数vses分别是构建时提供的顶点列表和边界列表(即,Graph(...))。对代码的粗略检查使得认为边是元组(v1, v2),其中v1v2是顶点。Graph是一个字典,其关键是从顶点;每个顶点映射到一个字典,其关键字是顶点。与self[a][b]相关联的值的存在意味着存在边缘a->b;代码暗示self[a][b] == self[b][a] == (a,b)

vs={}将创建一个本地名称vs指的是一个空的字典(vs=[]将使vs指空单)。一个正式的参数也是一个本地名称,但它是一个本地名称在呼叫时间初始化。