【问题标题】:How do I set my own global variables using input() in python 3.3?如何在 python 3.3 中使用 input() 设置我自己的全局变量?
【发布时间】:2013-03-22 19:49:01
【问题描述】:

所以我一直想知道一些我确信有一个非常简单的答案,但我似乎无法理解它。在一个函数中,我如何设置一个全局变量来执行某个任务。例如,我试过:

def function():
    global x
    x = input("Name of variable: ")
    x = print("Working")

我也试过了:


def function(Name_Of_Variable):
    global Name_Of_Variable
    Name_Of_Variable = print("Working") 

基本上,我只需要能够在函数中设置一个全局变量。我试图开始工作的实际代码是这样的:


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()

会发生这样的事情:

>>> htmlfrom("http://www.google.com")
What will this data be saved as: g
>>> g
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    g
NameError: name 'g' is not defined

注意事项:

  • Python 3.3
  • 全局变量(非本地)

【问题讨论】:

  • 我真的很好奇哪个 Python 教程告诉你使用全局变量...
  • 您是否尝试过以另一种不需要全局变量的方式解决问题?
  • 我还没有遵循 python 教程。据我所知,全局变量只是可以在任何地方访问的变量。为什么它们没有用,或者有没有更有用的方法?请详细说明。不,我没有尝试过另一种方式。有吗?
  • 在函数之间传递变量通常更好。

标签: function web python-3.x global-variables


【解决方案1】:

正如 cmets 中所讨论的:据我所知,不需要全局变量。 (如果这真的是你认为你需要的,我很乐意被说服。)

更模块化的编程方式是return 变量,从而允许您在函数之间传递数据。例如:

import urllib.request # `import` statements at the top! have a look at PEP 8

def htmlfrom(website_url):
    ''' reads HTML from a website 
        arg: `website_url` is the URL you wish to read '''
    response = urllib.request.urlopen(website_url)
    return response.read()

然后假设您要为多个网站运行此功能。您可以将 HTML 存储在 dictlist 或其他数据结构中,而不是为每个网站创建变量。例如:

websites_to_read = ('http://example.com',
                    'http://example.org',)

mapping_of_sites_to_html = {} # create the `dict`

for website_url in websites_to_read:
    mapping_of_sites_to_html[website_url] = htmlfrom(website_url)

【讨论】:

  • 也许FIRST函数中不需要全局变量,但是当我想要来自多个网站的html时呢?这就是为什么我需要多个变量,对吧?
  • 您不需要多个变量。请考虑将多个站点的 HTML 存储在 dictlist 或其他数据结构中。
  • 代码在字典中看起来如何?我不知道如何将它们与不同的变量一起存储在字典中。
猜你喜欢
  • 2013-08-16
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 2021-09-01
  • 2019-06-13
相关资源
最近更新 更多