0

I am seeing python class examples inside the class few functions are using double underscore, and few functions it starts single underscore and for some functions they does not use underscore.

Is this only to differentiate the code? or If we use differently like double underscore or single underscore code behaves differently.

Below is the script i found it has double underscore, single underscore and without under score.

import paramiko
import socket

class NetappFiler:

    def __init__(self, host, username, password, port=22):
        # Create ssh client
        self.client=paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(host, port , username=username, password=password)


    def __del__(self):
        # Close ssh connection
        self.client.close()    


    def ssh_cmd(self, cmd):
        #print (cmd)
        stdin, stdout, stderr = self.client.exec_command(cmd)
        stdin.close()
        stdout = stdout.readlines()
        return stdout

    def _ssh_yes_cmd(self, cmd):
        #print (cmd)
        stdin, stdout, stderr = self.client.exec_command(cmd)
        stdin.write('y\n')
        stdin.flush()
        stdin.close()
        stdout = stdout.readlines()
        return stdout

    def _create_volume(self, vserver, vol_name, vol_size, target_aggr):
        # Creates a thick volume
        cmd = ("vol create -vserver %s -volume %s -aggregate %s -size %s "
               "-state online -type RW -policy default -user 0 -group 1 "
               "-security-style unix -unix-permissions ---rwxrwxrwx "
               "-max-autosize 60GB -autosize-increment 2.50GB "
               "-min-autosize 50GB -autosize-mode grow -space-guarantee volume"
               %(vserver, vol_name, target_aggr, vol_size))
        self.ssh_cmd(cmd)
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
kitty
  • 105
  • 1
  • 3
  • 16

1 Answers1

0

Two underscores at the beginning and at the end of a method:

When we see a method like __method__, it means it's a method which python calls.

For example, in your code __init__ and __del__ is such a method. When you do the following.

obj = NetappFiler(arg1, arg2, arg3) # __init__ gets called
del obj # __del__ gets called

Single underscore at the beginning:

Python doesn't have real private methods, so one underscore at the start of a method or attribute name means, it is private to that class.

From PEP-8:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

To learn more, please read the Descriptive: Naming Styles section from the document.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • 1
    The part about `del` is incorrect. That only decreases the ref count, it doesn't necessarily call `__del__`. – wim Jun 11 '17 at 23:05