Python classes - Tips on class variables, class methods, and the "self" argument

In the action tutorial there are action server code examples, containing this:

class MoveSquareClass(object):

  # create messages that are used to publish feedback/result
  _feedback = TestFeedback()
  _result   = TestResult()

  def __init__(self):
    # creates the action server

why are _feedback and _result defined before the class constructor, and why do they not need “self.” in front of them?

@simon.steinmann91,

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:
def test_instance_method(self):
    # These two will be the same
   MoveSquareClass._feedback
   self._feedback
  • Because they are variables and not methods, they can’t receive the self argument.

About self

  • 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:

@classmethod
def test_class_method(cls):
    # Do some class-level work

# class methods can be called these ways
#1. Called anywhere where the class has been imported
MoveSquareClass.test_class_method()

#2. Called with any instance method of the class
def call_class_method_within_instance_method(self): 
    # Either a or b will work
    self.test_class_method() #a
    MoveSquareClass.test_class_method() #b

For more information, take a look at our FREE Python 3 for Robotics course to learn more about the Python programming language.

2 Likes