The self argument

Hello,

I’m following the Python for Robotics course and I’m woorking on Unit 4 - Methods. But when I take a look at the robot_control_class.py I see many time the argument self appearing. I’m trying to understand this. I have read another topic here where I saw a small explanation but I’m not sure if I understand it correct so I try to get the confirmation in this topic.

A small snippet of the robot_control_class.py is below.

    def __init__(self, robot_name="turtlebot"):
        rospy.init_node('robot_control_node', anonymous=True)

        if robot_name == "summit":
            rospy.loginfo("Robot Summit...")
            cmd_vel_topic = "/summit_xl_control/cmd_vel"
            # We check that sensors are working
            self._check_summit_laser_ready()
        else:      
            rospy.loginfo("Robot Turtlebot...")      
            cmd_vel_topic='/cmd_vel'
            self._check_laser_ready()

        # We start the publisher
        self.vel_publisher = rospy.Publisher(cmd_vel_topic, Twist, queue_size=1)
        self.cmd = Twist()        

        self.laser_subscriber = rospy.Subscriber(
            '/kobuki/laser/scan', LaserScan, self.laser_callback)
        self.summit_laser_subscriber = rospy.Subscriber(
            '/hokuyo_base/scan', LaserScan, self.summit_laser_callback)
        
        self.ctrl_c = False
        self.rate = rospy.Rate(1)
        rospy.on_shutdown(self.shutdownhook)

So now if I create a script and import the class and instantiate it as follows:

from robot_control_class import RobotControl

rc = RobotControl()

disValues = rc.get_laser_full()
maximum = 0

for dis in disValues:
    if dis > maximum:
        maximum = dis

print("Maximum distance is:", maximum)

Does the argument `self` basically says that I refer to the variable `rc`?

Thanks in advance

Hi @ElectricRay1981,

the self argument always refer to object itself.

“self” is a conventional variable name. You could easily use the “my” instead of “self” if you which.

To make it clearer, please analyze the following python code:

#! /usr/bin/env python3

name = 'Mecanical xRay'

class ElectricRay1981:

    name = 'Electric Ray'

    def say_name(my):
        print('My name is: ', my.name)
        print('And the external name is: ', name)


ray = ElectricRay1981()

ray.say_name()

If you run this command:

python3 ElectricRay1981.py

You would see the following output:

My name is:  Electric Ray
And the external name is:  Mecanical xRay

Can you see now the purpose of the “self” variable?
Please try to understand the code I posted here.

Cheers.

1 Like

Thanks thats a good and very fun explanation using my name :slight_smile:

Thanks for the clear explanation I appreciate!

1 Like

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