我已经搜索了所有的网络,并没有找到我的问题的答案。我试图理解一些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是包含该类信息的字典。
为什么使用{:}表示法?还有其他方法可以做到吗?
任何答案都非常感谢!
发布于 2017-04-07 09:37:35
只是恭维一下答案,这并不能解释令人困惑的代码。实际上,编写的代码非常令人困惑。这涉及到全球化和本地化的可变概念。
# 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)IMHO,这个例子是一些关于全局变量和局部变量的教程,以及糟糕的命名示例。
https://stackoverflow.com/questions/43272250
复制相似问题