对 python 语法感到困惑

Confused about python syntax

我在网上找遍了,但没能找到我的问题的答案。我试图理解一些 python 代码并遇到一个 class 声明,如下所示:

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 是包含有关 class 的信息的字典。

为什么使用 {:} 符号?有没有其他方法可以做到这一点?

非常感谢任何答案!

{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!

中还有其他一些创建字典的方法

只是恭维答案,并没有解释混乱的代码。 确实,代码写得相当混乱。这涉及到全局化和本地化变量的概念。

# 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)

恕我直言,该示例是某种教程,旨在教授全局变量与局部变量,以及错误的命名示例。