[英]Confused about python syntax
我在網上瀏覽了所有內容,卻找不到我的問題的答案。 我試圖理解一些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是包含有關類的信息的字典。
為什么使用{:}符號? 還有其他方法可以做到嗎?
任何答案非常感謝!
{curr_date:difference}
創建了一個匿名字典。 {curr_date:difference}
,您可以創建一個名稱為的字典:
dict_name={}
dict_name[curr_date]= difference
self.s_list=dict_name
另外,您甚至可以使用dict()
創建字典: self.s_list=dict(curr_date=difference)
還有其他一些方法可以在python中創建字典!
只是對答案的補充,並沒有解釋令人困惑的代碼。 確實,編寫的代碼非常令人困惑。 這涉及全球化和局部變量概念。
# 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)
恕我直言,該示例是某種教程,旨在指出有關全局變量與局部變量以及命名錯誤的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.