动态全局变量分配 [英] Dynamic global variables assignment

查看:200
本文介绍了动态全局变量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,在使用 global 指令时遇到很多麻烦。

这是一个代码示例:

I'm new in python and I'm having many troubles in using global instruction.
Here is a code example:

mouse = "a"
background = "b"

list_ab = [mouse, background]

def func ():
    for item in list_ab:
        global item  # I want to modify the GLOBAL item, which is mouse
                     # and background.
        item = "modified"
    print mouse  # must be "modified" not "a"
    print background  # must be "modified" not "b"

这是问题所在。我该怎么解决?

This is the problem. How can I solve it?

推荐答案

您的问题是Python的工作方式与您的想法不同。

因此,我将尝试逐行解释代码中发生的事情。

Your problem is that Python works not the way you think.
So I will try to explain what's going on in your code, line by line.

mouse = "a"

将字符串 a分配给名称 mouse

Assigns the string "a" to the name mouse.

background = "b"

将字符串 b分配给名称 background

Assigns the string "b" to the name background.

list_ab = [mouse, background]

分配两个对象,名称用<$引用c $ c>鼠标和背景,进入列表 list_ab

正如我们已经知道的,它们是常数 a和 b。因此,您可以这样写:

Assigns two objects, referenced by names mouse and background, to the list list_ab.
As we already know, they are constants "a" and "b". So you can just write:

list_ab = ["a", "b"]

现在循环

for item in list_ab:

将列表中的每个对象分配为名称 item

对于第一次循环迭代,这意味着 item = a

assigns each object in the list to the name item.
For the first loop iteration, it means item = "a".

    global item # I want to modify the GLOBAL item, which is mouse ad background

没有任何意义,因为它试图告诉Python名称 item 是全局的,而没有声明这样的全局变量。

doesn't make sense, because it tries to tell Python that the name item is global, while there is no such global variable declared.

对于在线上最令人困惑的行为

And for the most confusing behavior on the line

    item = "modified"

只需了解一下,虽然它将字符串 modified分配给名称 item ,但字符串 a和 b仍然相同,并且仍分配给列表 list_ab (和nam es 鼠标背景,您也没有碰过)。

you should just understand that while it assigns the string "modified" to the name item, strings "a" and "b" are still the same, and still assigned to the list list_ab (and names mouse and background, which you didn't touch either).

名称 item 本身仅存在于声明的范围内,当 for循环结束时,它被破坏了。
每次迭代时,它还会重新分配 list_ab 中的下一个项目。

The name item itself lives only in the scope where it was declared, when the "for" loop ends, it's destructed. It is also reassigned every iteration with the next item from the list_ab.

到总结一下:

如果您想为列表中的项目分配修改过的字符串,请直接执行:

If you want to assign "modified" string to the items in the list, do it directly:

list_ab[0] = "modified"
list_ab[1] = "modified"

如果需要更改在全局范围内声明的变量,请执行以下操作:

If you need to change variable declared in the global scope, do this:

mouse = "a"

def func():
    global mouse   # tell Python that you want to work with global variable
    mouse = "modified"

func()
print mouse # now mouse is "modified"

基于问题的第一个修订版本的示例:

而不是

background = g_base("bg.jpg") # g_base class instance
mouse = g_base("mouse.png",alpha=1) # g_base class instance

imgs_to_load = [mouse, background]

def Image_loader (img):
    # ..... code to load the image and convert it into pygame surface...
    return img_load

def main ():
    for image in img_to_load:
        global image
        image = Image_loader (img)
        print image # if I print image, it is a pygame surface

    print background # But here, outside the loop, image is still a g_base instance ?!?!
    print mouse # " "   

main()

您可以做到:

imgs_to_load = [g_base("bg.jpg"), g_base("mouse.png",alpha=1)] # list with a g_base class instances

def Image_loader(img):
    # ..... code to load the image and convert it into pygame surface...
    return img_load

def main ():
    imgs_in_pygame_format = [] # create an empty list
    for image in imgs_to_load:
        loaded_image = Image_loader(image) 
        imgs_in_pygame_format.append(loaded_image) # add to the list 

    for image in imgs_in_pygame_format:
        print image # every image in the list is a pygame surface

    # or
    print image[0]
    print image[1]

main()

或者如果您想按名称引用图像,则可以将其放入字典中。

Or if you want to reference to images by name, you can put them into dictionary:

imgs_to_load = {} 
imgs_to_load["bg"] = g_base("bg.jpg")
imgs_to_load["mouse"] = g_base("mouse.png",alpha=1)

imgs_in_pygame_format = {} # create a global dictionary for loaded images

def main ():
    global imgs_in_pygame_format # import that global name into the local scope for write access
    for name, data in imgs_to_load.items():
        imgs_in_pygame_format[name] = Image_loader(data) # add to the dictionary

    for image in imgs_in_pygame_format:
        print image # every image in the dictionary is a pygame surface

    # or    
    print imgs_in_pygame_format["bg"]
    print imgs_in_pygame_format["mouse"]

main()

但最重要的是,全局变量不是一个好主意。更好的解决方案是使用一个类:

But most importantly, global variables are bad idea. The better solution would be to use a class:

def Image_loader(img):
    # ..... code to load the image and convert it into pygame surface...
    return img_load

class Image:
    def __init__(self, image):
        self.data = Image_loader(image)

def main ():
    bg = Image(g_base("bg.jpg"))
    mouse = Image(g_base("mouse.png",alpha=1))

    print bg.data
    print mouse.data

main()

有关更多示例,请参见 Python教程

For more examples see Python Tutorial.

希望有帮助,欢迎使用StackOverflow!

Hope it helps, and welcome to StackOverflow!

这篇关于动态全局变量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆