我想知道为什么在函数结束后我无法访问变量:“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 NOT urllib2
答案 0 :(得分: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语句,它只能访问 功能(即其他功能无法访问)
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_name = input("What will this data be saved as: ")
html_from_website = htmlfrom("www.stackoverflow.com")
您可以详细了解上下文管理器here
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()