Python class for simple subscriber

Hi there, I am trying to get subscriber data using python classes. I am bit confused regarding one step and would like to understand that why we are assigning the self.msg = msg after assigning self.msg = Int32(). I have attached the picture below.image. I mean why can’t we directly print the self.msg in the sub_callback function as we already assigned Int32() value to it. Why do we again need to assign the self.msg to msg variable again when def sub_callback() function has access to the self.msg = Int32() variable. First we are assigning Int32() value to self.msg and then we are assigning msg to the self.msg again, then how will the value of Int32() get stored in msg. I would simply like to understand that how does this self.msg varaiable is working as we are assiging 2 values to the same variable. Also, in the procedural style we were using as shown below image. In class I didn’t use but still got the correct answer, what is the reason behind this. Cheers.

In the statement

self.msg = Int32()

we did not assign; we declared that self.msg is a variable of the type (class) Int32. You can know this because we have a () at the end.

The other statement is an assignment.

If you wanted to create a variable of your class, you would write a similar statement:

my_subscriber = Subscriber()

As mentioned above, the first statement is a declaration and the second is an assignment.

  • When we declared self.msg, it became a variable of type Int32 with default values (probably zeroes)
  • The subscriber will send some data to sub_callback(self, msg) from time to time. This data will be of the type Int32 (as defined in the statement that created the subscriber) and will be stored in msg.
  • In the assignment statement, we are assigning the values sent by the subscriber to self.msg. Because self.msg is available to all methods of the class, this means we can access the updated data from the subscriber from anywhere the class.
  • We could use the msg variable from the subscriber directly in sub_callback without assigning it to self.msg, but then it won’t be available in other methods of the class.
  • Even though self.msg and msg look similar and belong to the same type (Int32), they are two different variables. For clarity, you could define your callback method as something like this:
def sub_callback(self, msg_from_sub):
   self.msg = msg_from_sub
1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.