在Python 3中从函数创建全局变量
我在想,为什么在函数结束后我不能访问这个变量:“variable_for_raw_data”?代码是这样的:
def htmlfrom(Website_URL):
import urllib.request
response = urllib.request.urlopen(Website_URL)
variable_for_raw_data =(input("What will this data be saved as: "))
global variable_for_raw_data
variable_for_raw_data = response.read()
那么,为什么在函数结束后我不能访问“variable_for_raw_data”这个变量呢?
需要注意的几点:
使用的是Python 3.3
用的是urllib,而不是urllib2
1 个回答
1
看起来你想动态创建变量,我想你的代码大概是这样的。
def htmlfrom(website_url):
import urllib.request
response = urllib.request.urlopen(website_url)
variable_for_raw_data =(input("What will this data be saved as: "))
global variable_for_raw_data
variable_for_raw_data = response.read()
if __name__ == "__main__":
htmlfrom("www.stackoverflow.com")
#html_stackoverflow is never created it is the value
#of variable_for_raw_data before variable_for_raw_data
#is overridden by response.read()
#entering information into input doesn't create a variable
print(html_stackoverflow)
这是我会怎么做:
import urllib.request
def htmlfrom(website_url):
'''
docstrings
'''
response = urllib.request.urlopen(website_url)
variable_for_raw_data = response.read()
return variable_for_raw_data
if __name__ == "__main__":
file_name = input("What will this data be saved as: ")
html_from_website = htmlfrom("www.stackoverflow.com")
with open(file_name, 'w') as f:
f.write(html_from_website)
解释
如果你把导入语句放在函数里面,那么这个导入的东西只能在这个函数里用(也就是说其他函数是不能用的)
import urllib.request
PEP 8 有一些关于在 Python 中命名的指导原则,通常大写驼峰命名法(CamelCase)是用来命名类的。
def htmlfrom(website_url):
'''
docstring
'''
文档字符串(Docstrings) 通常是个好主意。
你可以查看这个问题,了解如何正确使用 全局变量(globals)。根据我对你情况的了解,我觉得你不需要使用它们。
response = urllib.request.urlopen(website_url)
variable_for_raw_data = response.read()
return variable_for_raw_data
如果你不知道 `if name == 'main': 是什么,你应该去了解一下。
if __name__ == "__main__":
别忘了使用有意义的变量名,不要覆盖掉 内置函数(builtins)(比如 file = "foo.txt" 会覆盖掉内置的 file 函数)。
file_name = input("What will this data be saved as: ")
html_from_website = htmlfrom("www.stackoverflow.com")
你可以在 这里 学习更多关于上下文管理器(context managers)的知识。
with open(file_name, 'w') as f:
f.write(html_from_website)
这是一个使用 globals()
的编辑,但根本没有任何使用场景。
def htmlfrom(website_url):
import urllib.request
response = urllib.request.urlopen(website_url)
variable_for_raw_data =(input("What will this data be saved as: "))
globals()[variable_for_raw_data] = response.read()