混淆全局函数

huangapple go评论79阅读模式
英文:

Confusion with global funtion

问题

我已经在ROS中使用Python编写了一段代码。所以我的代码做的事情很简单,调用一个名为'callback'的函数。我的问题出在这个回调函数上,因此这成了Python中的一个问题。

当我在回调函数内部定义'global var',然后在回调函数内部定义其类型(var=Twist(),即代码的第二行和第三行在回调函数内部),我会得到一个错误,错误消息是'var is not defined'。

类似地,如果我在回调函数外部定义'global var',然后在回调函数内部定义其类型(var=Twist()),也会出现相同的问题。但是我已经看到一些示例中全局变量是在函数内部定义的。

以下是我的代码的相关部分:

pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
global var
var = Twist()

def callback(msg):
    v = msg.ranges
    if v[360] < 1:
        var.angular.z = 0.5
        var.linear.x = 0
    else:
        if v[719] < 1:
            var.angular.z = -0.3
            var.linear.x = 0
        elif v[0] < 1:
            var.angular.z = 0.5
            var.linear.x = 0
        else:
            var.linear.x = 1
            var.angular.z = 0
    print('var value is', var)

rate = rospy.Rate(2)

while not rospy.is_shutdown():
    sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, callback)
    pub.publish(var)
英文:

I have written a code in ROS using python. So what my code does is something simple and calls a function 'callback'. My problem is with the callback function so this ends up as a problem in python.

When I define 'global var' inside the callback function and then define its type(var=Twist()) inside the callback function(i.e the 2nd and 3rd line of code are inside the callback function), I get an error as 'var is not defined'.
Similarly for the case when I define 'global var' outside the callback function and then define its type(var=Twist()) inside callback. But I have seen examples where global variables are defined inside the function.
Here is relevant part of my code.

    pub = rospy.Publisher(&#39;/cmd_vel&#39;, Twist, queue_size=1)
    global var
    var=Twist()
    def callback(msg):

    v=msg.ranges
    if v[360]&lt;1:
        var.angular.z=0.5
        var.linear.x=0
    else:
        if v[719]&lt;1:
            var.angular.z=-0.3
            var.linear.x=0
        elif v[0]&lt;1:
            var.angular.z=0.5
            var.linear.x=0
        else:
            var.linear.x=1
            var.angular.z=0
    print(&#39;var value is&#39;,var)

        

rate = rospy.Rate(2)

while not rospy.is_shutdown():
sub = rospy.Subscriber(&#39;/kobuki/laser/scan&#39;,LaserScan , callback)
pub.publish(var)

答案1

得分: 0

当使用 global 关键字时,变量的定义需要是全局的(在 callback() 函数的作用域之外),并且 global 关键字需要在作用域内。请参见此处的示例 #3。

英文:

When using the global keyword, the definition of the variable needs to be global (outside of the scope of the callback() function) AND the global needs to be inside the scope. See example #3 here.

huangapple
  • 本文由 发表于 2020年1月4日 01:52:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/59583123.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定