Hi,
Why aren’t feedback and results variables defined within class initialization?
Thanks
Hi,
Why aren’t feedback and results variables defined within class initialization?
Thanks
#! /usr/bin/env python
import rospy
import actionlib
from actionlib_tutorials.msg import FibonacciFeedback, FibonacciResult, FibonacciAction
class FibonacciClass(object):
_feedback = FibonacciFeedback()
_result = FibonacciResult()
def init(self):
# creates the action server
self._as = actionlib.SimpleActionServer(“fibonacci_as”, FibonacciAction, self.goal_callback, False)
self._as.start()
…
The feedback and results variables are defined outside the class initialization. Why?
Oh…that’s Python magic .
Those are class variables (versus instance variables ). Initialization applies only to instance variables, which can vary from one instance of the class to another. Class variables, on the other hand, are variables that don’t need to change accross instances (usually they are constants) and can be accessed directly from the class or from any instance of the class. So you can do the following:
# Directly from anywhere where FibonacciClass is available
feedback = FibonacciClass._feedback
result = FibonacciClass._result
# From an instance method of the class
def instance_method(self):
result = self._result
feedback = self._feedback
# From a class method of the class
@classmethod
def class_method(cls):
result = cls._result
feedback = cls._feedback
Is it clear?