我不明白这个 Python 代码是如何工作的 - 未知的编程概念
I do not understand how this Python code works - Unknown programming concept
我为糟糕的标题道歉。如果我能够正确地构建我的问题,我会使用 google ;)
我发现一段 python 代码能够将 ini 文件解析为 python 名为 "store" 的字典:
#!/usr/bin/env python
from ConfigParser import SafeConfigParser
def read(file, store):
def parse_maybe(section):
if not confp.has_section(section):
return False
if (section == "Main"):
for left, right in confp.items(section):
store[left] = right.format(**store)
return True
confp = SafeConfigParser()
confp.read(file)
parse_maybe("Main")
store = {}
store["basedir"] = "/path/to/somewhere"
read("foo.ini", store)
ini 文件可能包含带有占位符的声明,例如:
[Main]
output = {basedir}/somename.txt
当 运行 代码时,{basedir} 被存储中已定义的“/path/to/somewhere”替换。我想这个魔法来自这行代码:
store[left] = right.format(**store)
我理解代码的作用。但我不明白如何这是有效的。这个 ** 运算符用字典做什么?非常感谢指向教程等的指针。
我的问题有两个答案:
1) 我不知道格式可以这样:
print "{a} is {b}".format(a="Python", b="great")
Python很棒
2) 本质上**运算符解压字典:
dict = {"a": "Python", "b": "great"}
print "{a} is {b}".format(**dict)
Python很棒
我为糟糕的标题道歉。如果我能够正确地构建我的问题,我会使用 google ;)
我发现一段 python 代码能够将 ini 文件解析为 python 名为 "store" 的字典:
#!/usr/bin/env python
from ConfigParser import SafeConfigParser
def read(file, store):
def parse_maybe(section):
if not confp.has_section(section):
return False
if (section == "Main"):
for left, right in confp.items(section):
store[left] = right.format(**store)
return True
confp = SafeConfigParser()
confp.read(file)
parse_maybe("Main")
store = {}
store["basedir"] = "/path/to/somewhere"
read("foo.ini", store)
ini 文件可能包含带有占位符的声明,例如:
[Main]
output = {basedir}/somename.txt
当 运行 代码时,{basedir} 被存储中已定义的“/path/to/somewhere”替换。我想这个魔法来自这行代码:
store[left] = right.format(**store)
我理解代码的作用。但我不明白如何这是有效的。这个 ** 运算符用字典做什么?非常感谢指向教程等的指针。
我的问题有两个答案:
1) 我不知道格式可以这样:
print "{a} is {b}".format(a="Python", b="great")
Python很棒
2) 本质上**运算符解压字典:
dict = {"a": "Python", "b": "great"}
print "{a} is {b}".format(**dict)
Python很棒