Python syntax clarification in ex 2.1

I’m working on exercise 2.1, and I’m curious about some syntax effects.
For this solution:

#! /usr/bin/env python

import rospy
from geometry_msgs.msg import Twist

rospy.init_node('move_robot_node')
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
rate = rospy.Rate(2)
move = Twist()
move.linear.x = 0.5 #Move the robot with a linear velocity in the x axis
move.angular.z = 0.5 #Move the with an angular velocity in the z axis

while not rospy.is_shutdown(): 
  pub.publish(move)
  rate.sleep()

if we alter interact with move in this way:

move = Twist()
move_x = move.linear.x 
move_x = 0.5
move_z = move.angular.z
move_z = 0.5

The the exact same program no longer works. To some extent, I feel like that’s obvious, because we’ve reset move_x and move_z to 0.5, not parts of move anymore. However, I think I remember being able to do something like this in python before, but I can’t find the old code I had. Can you tell me if I’m mis-remembering/there’s another way to achieve that? Surely in longer code it gets unweildly to keep typing out move.angular.z etc.

(Is this the right place to post this/an ok question to ask here?)

Hi @elizabeth.wills,
In python you usually use classes and functions like this:

def move_msg(x,z):
    move = Twist()
    move.linear.x = x
    move.angular.z = z
    return move 

move = move_msg(0.5, 0.5)
while not rospy.is_shutdown(): 
  pub.publish(move)
  rate.sleep()

Hope that helps

Thank you! I appreciate the suggestion and explanation.

2 Likes

Oh I noticed the function is wrong, it of course has to be:

def move_msg(x,z):
    move = Twist()
    move.linear.x = x
    move.angular.z = z
    return move 
1 Like