2017-04-07 192 views
0

我已經瀏覽了所有的網頁,一直未能找到我的問題的答案。我想了解一些Python代碼和跨類聲明,看起來像這樣走過來:關於python語法的困惑

s_list = []  
last_name = "" 

def __init__(self, last_name, curr_date, difference): 
    self.last_name = last_name 
    self.s_list = {curr_date:difference} 
    self.d_list = [] 
    self.d_list.append(curr_date) 

什麼是花括號內發生了什麼?這是初始化字典嗎?後來在主文件,它使用的是這樣的:

n = n_dict[last_name] 
n.d_list.append(curr_date) 
n.s_list[curr_date] = difference 

其中n是用於添加到n_dict,與n_dict是一個包含類信息的字典,一個臨時的字典。

爲什麼使用{:}符號?有沒有其他方式可以做到這一點?

任何答案非常感謝!

+3

https://docs.python.org/2/tutorial/datastructures.html#dictionaries –

+1

是的,'{curr_date:difference}'初始化字典。它也可以寫成'dict(((curr_date,difference),))''。 – timgeb

+1

公平地說,'s_list'對於字典來說是一個很差的名字。它被Python所忽視,但它讓下一個開發者更難理解發生了什麼。 –

回答

1

{curr_date:difference}創建一個匿名dictionary.Instead,您可以創建一個字典,一個名字:

dict_name={} 
dict_name[curr_date]= difference 
self.s_list=dict_name 

而且,你甚至可以創建一個字典使用dict() self.s_list=dict(curr_date=difference)

還有一些其他的方法在Python中創建一個字典!

+5

「字典文字」,而不是「匿名字典」。 –

+0

謝謝!你的陳述是正確的! – nick

+0

'dict_name',不只是'dict'。另外:「一個名字的字典」。它不會這樣工作:'AttributeError:'dict'對象沒有'name'屬性。你剛剛用一個dict對象初始化了一個變量。這並不意味着這個詞典對象有一個名字 –

0

只是讚揚答案,這並沒有解釋混淆的代碼。 確實,代碼寫得很混亂。這涉及全球化和局部變量概念。

# This is the global list variable 
s_list = []  

# this is the global 
last_name = "" 

def __init__(self, last_name, curr_date, difference): 
    # Everything define here is localised and will be used first 
    # pass value from given to last_name (not using above global last_name) 
    self.last_name = last_name 

    # This localised assignment make self.s_list a dictionary 
    self.s_list = {curr_date:difference} 
    # create another list 
    self.d_list = [] 
    self.d_list.append(curr_date) 

恕我直言,這個例子某種教程指向講授與壞的命名實例全局VS局部變量,和在一起。