0

我想知道为什么我不能在函数结束后访问变量:“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

4

1 回答 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 
    '''

文档字符串通常是个好主意。

查看此问题以获取有关正确使用globals的更多信息。根据我对您的情况的了解,我认为您不需要使用它们。

    response = urllib.request.urlopen(website_url)
    variable_for_raw_data = response.read()
    return variable_for_raw_data

如果您不了解`if name == ' main ':您应该阅读它。

if __name__ == "__main__":

不要忘记使用有意义的变量名并且不要覆盖 内置函数(即 file = "foo.txt" 将覆盖内置文件)

    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)

使用 的编辑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()
于 2013-03-21T17:06:38.747 回答