英文:
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('/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)
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论