In the action tutorial there are action server code examples, containing this:
# create messages that are used to publish feedback/result
_feedback = TestFeedback()
_result = TestResult()
# creates the action server
_result defined before the class constructor, and why do they not need “self.” in front of them?
Those variables defined before
__init__ are class variables:
About class variables:
- They are shared - not intended to be changed per instance, and cannot be changed unless they are mutable.
- Changing class variables involving mutable objects can have unintended effects, as per the discussion here.
- Class variables are available to all instances of the class. They can be accessed via the class or instance object, e.g:
# These two will be the same
- Because they are variables and not methods, they can’t receive the
self is the first argument that every instance method gets.
self is a variable representing the instance of the class.
def __init__(self) is a special instance method that is run when a new instance of the class is created. It can be used for setting default values for instance variables and/or running custom code.
Bonus: class methods
We also have class methods, usually defined this way:
# Do some class-level work
# class methods can be called these ways
#1. Called anywhere where the class has been imported
#2. Called with any instance method of the class
# Either a or b will work
For more information, take a look at our FREE Python 3 for Robotics course to learn more about the Python programming language.