从python中的函数外部访问变量 [英] accessing a variable from outside the function in python

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

问题描述

#!/usr/bin/env python
import roslib
import rospy
import time
from nav_msgs.msg import Odometry 

def position_callback(data):
    global q2
    q2=data.pose.pose.position.x
    q1=data.pose.pose.position.y
    q3=data.pose.pose.position.z


def position():      
    rospy.init_node('position', anonymous=True)  #initialize the node"
    rospy.Subscriber("odom", Odometry, position_callback)

if __name__ == '__main__':

    try:
        position()
        print q2
        rospy.spin()
    except rospy.ROSInterruptException: pass

我得到的错误是这样的:

the error i get is like this:

print q2
NameError: global name 'q2' is not defined

我已经将 q2 定义为全局变量.

I defined q2 as global variable already.

推荐答案

q2 声明为全局变量确实会使全局变量存在.

Declaring q2 as a global variable does make the global variable exist.

实际上调用函数并执行赋值语句q2 = ... 导致变量的创建.在此之前,代码无法访问该变量.

Actually calling the function and execution of the assignment statement q2 = ... cause the creation of the variable. Until then, the code cannot access the variable.

position 函数不调用 position_callback,而是将它传递给 rospy.Subscriber(它可能注册了回调函数,而不是调用直接).

position function does not call the position_callback, but pass it to rospy.Subscriber (which probably register the callback function, and not call it directly).

如果您想在设置之前访问该变量,请初始化 q2.

Initialize q2 if you want to access the variable before it is set.

q2 = None

def position_callback(data):
    global q2
    q2 = data.pose.pose.position.x
    q1 = data.pose.pose.position.y
    q3 = data.pose.pose.position.z

这篇关于从python中的函数外部访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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