在python中更改函数内的全局变量 [英] changing global variables within a function in python

查看:59
本文介绍了在python中更改函数内的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.

I'm new to python.

我不太明白我需要如何设置变量并在稍后使用的函数中更改它们.我的脚本需要从函数中获取 x 和 y 值,这些值由函数创建的图表的大小决定.这些变量需要稍后在脚本中传递给打印命令以输出 html.假设我有全局变量:

I don't quite understand how I need to set variables and change them within a function to be used late. My script needs to get an x and y value from a function which are determined by the size of the chart the function creates. These variable need to be passed to a print command later in the script to output html. So let's say I have global variables:

    originx_pct = 0.125
    originy_pct = 0.11

但是当函数运行时这些需要改变......

But these will need to change when the funtion is run...

    def makeplot(temp, entropy,preq):
        originx_pct = origin.get_points()[0][0]
        originy_pct = origin.get_points()[0][1]

然后在后面写的html页面的javascript里面打印...

Then printed within the javascript of the html page that is written later...

    print('var originx_pct = {};'.format(originx_pct))
    print('var originy_pct = {};'.format(originy_pct))

这两个变量不会改变,我只是不明白我需要做什么来更新它们并能够打印它们(在函数之外).我假设函数不知道变量,所以它不能改变它们.如果我将 2 个变量作为参数提供给函数,我如何为脚本的打印部分取回值?

The 2 variables don't change and I just don't understand what I need to do to update them and be able to print them (outside the function). I'm assuming that the function does not know about the variables so it can't change them. If I feed the function the 2 variables as arguments, how do i get the values back out for the print part of the script?

推荐答案

您需要在函数中使用 global 关键字.

You need to use the global keyword in your function.

originx_pct = 0.125
originy_pct = 0.11

def makeplot(temp, entropy,preq):
    global originx_pct, originy_pct
    originx_pct = origin.get_points()[0][0]
    originy_pct = origin.get_points()[0][1]

您可以在此处阅读有关global的更多信息.

You can read more about global here.

这篇关于在python中更改函数内的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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