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:
Why is the _move_msg attribute being initially defined in the goal_callback method instead of the init method?
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?
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?
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.
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.