Class attributes not initialized within _init_ method (ROS 5 Days, Topic 8)

A (not-so)quick question regarding class attributes :

From what I’ve learnt regarding classes(still rather shallow i feel), i always thought it was good programming practice to define any attributes that will be used in the class within the_init_ method. However for exercise “8.13”, after a quick Ctrl+F in the code i realized that the attribute _move_msg is defined within goal_callback as a Twist() message type and the methods above it are altering the fields within this Twist() instance.

So back to my questions:

  1. Why is the _move_msg attribute being initially defined in the goal_callback method instead of the init method?

  2. Isn’t an attribute local to the method if it isn’t defined within init? If so, how is it possible that turn_drone_ and move_forward_drone methods are calling a local method within the goal_callback method?

  3. This might be similar to question 2, but why isn’t an AttributeError raised if the variable isn’t first defined in the init method?

Hi,

You could define it within init just like you said, but if you pay attention to the comments, you’ll see that the attribute _move_msg is defined in the callback function that is called when the action server is called (the first line in init). That’s why the attribute is defined before any other methods use it.

1 Like
  1. I agree that the code would be easier to understand if that attribute was defined within __init__, but it works nevertheless as @roalgoal mentioned.

  2. That rule only applies to ordinary Python variables, but this is an instance attribute (or variable) defined with the self keyword; it automatically becomes available to all other methods of the class from that point onwards.

  3. See point 2 above.

1 Like

Hi, one last question. After doing a few more exercises, I realized this way of creating publisher objects and messages within the goal_callback method instead of init method is always done in all of them. Is there any particular reason/advantage for us to define the publishers and messages within the goal_callback method instead of init?

I don’t think there’s a measurable advantage in a simple code like this, rather more of a preference of the coder. In this case, the advantage of defining publishers (and more importantly, subscribers) within a callback is that you make sure that the action server will call on the callback every time it’s executed. This is good practice for things like topics or other continuous information.

1 Like