0

im confused with use of def __init__ in a class definition. im new, so problem is not understanding why the hell i needed it - if i dont have to define variables in the class:

here is a paramiko ssh connection object, in which i have commented out the def__init__(self), and my code seems to work. if i uncomment the line, i get an error about indent because there is no code underneath the def __init__. Im partly concerned because I reference self in the other functions to perform more actions in the instance. it seems to know what self is, even though i haven't init-ed it.

  File "XXXX", line 517
    def sshCLIENT(self):
    ^
IndentationError: expected an indented block after function definition on line 515
class SSHCONN():  #paramiko connection object class for SSH logins
    '''http://http://www.paramiko.org/'''
    
    #def __init__(self):
        
    def sshCLIENT(self):
        try:
            self.sshSESS = paramiko.SSHClient()  #instantiate SSH session object
            self.sshSESS.set_missing_host_key_policy(paramiko.AutoAddPolicy())  #auto add host SSH key - must trust
            return True
        except:
            return False
            
    def CONNECT(self, IP, U, P, validPWD=True, Port=22):
        PwdShow = P if validPWD == False else '<PwdHidden>'
        
        try:
            LogDrop(f'Login Attempt to \'{IP}\' with: \'{U} / {PwdShow}\'')
            ##paramiko needs keyword arguments for logins, cannot use positional
            self.sshSESS.connect(hostname=IP, username=U, password=P, look_for_keys=False, allow_agent=False, timeout=5)
            return True
            
        except paramiko.ssh_exception.AuthenticationException:
            LogDrop(f'Connection to \'{IP}\' failed with: \'{U} / {PwdShow}\', due to bad username or password.')
            LogDrop('...')
            self.sshSESS.close()
            return False
            
        except paramiko.ssh_exception.SSHException:
            LogDrop(f'Connection to \'{IP}\' failed, probably due to SSH2 protocol negotiation errors.')
            LogDrop('...')
            self.sshSESS.close()
            return False
            
        except paramiko.ssh_exception.NoValidConnectionsError:
            LogDrop(f'Connection to \'{IP}\' failed, probably due SSH not listening.')
            LogDrop('...')
            self.sshSESS.close()
            return False
            
        except:
            LogDrop(f'Connection to \'{IP}\' failed, probably due to host not online.')
            LogDrop('...')
            selfsshSESS.close()
            return False

    def CLOSE(self, IP=None):
        if IP == None: IP = 'server'
        else: IP = "\'" + IP + "\'"
        
        self.sshSESS.close()
        LogDrop(f'SSH connection successfully closed to: {IP}')
                
    def SFTPOPEN(self, IP=None):
        if IP == None: IP = 'server'
        else: IP = "\'" + IP + "\'"
        
        try:
            self.sshSESS.open_sftp()
            return True
            
        except:
            LogDrop(f'SFTP session opened failed to {IP}; likely due to SFTP not running or configured.')
            LogDrop('...')
            self.sshSESS.close()
            return False

    def SFTPPUT(self, IP, file, strRmtSubDir): 
        try:
            LogDrop(f'Transferring file {os.path.basename(file)} to server: {IP}')
            LogDrop(f'at remote location: {strRmtSubDir}/{os.path.basename(file)}')
            self.sshSESS.open_sftp().put(file, strRmtSubDir.rstrip("/") + "/" + os.path.basename(file)) #if user has ending "/", rstrip it
        except FileNotFoundError as error:
            LogDrop(f'Unable to move file: {error}')
        except:
            LogDrop('Unexpected error: ', sys.exc_info())
            sys.exit(1)

    def SFTPCLOSE(self, IP=None):
        if IP == None: IP = 'server'
        else: IP = "\'" + IP + "\'"
        
        try:
            self.sshSESS.open_sftp().close()
            LogDrop(f'SFTP Channel successfully closed to: {IP}')
        except:
            LogDrop(f'SFTP Channel failed to close to: {IP}')
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • Does this answer your question? [How to use the pass statement](https://stackoverflow.com/questions/13886168/how-to-use-the-pass-statement) – jtbandes Jul 30 '22 at 04:22

1 Answers1

1

You do not need to define a constructor in Python if it serves you no purpose. Python will provide a default constructor if no constructor is defined. It does not do anything except initialize your object. Rest assured, your references to self will work exactly the same way as if you had defined an empty constructor with no body.

Also the reason you seem to be getting an indentation error is because the interpreter expects the next line after def __init__(self): to be a part of the __init__ function you can instead is define an empty constructor with no body as follows:

def __init__(self):
    pass
#Rest of your code as it is
Sarah N
  • 101
  • 1
  • "constructor" is not the right term here, `__init__` merely initializes an already constructed object. – tdelaney Jul 30 '22 at 04:29
  • just wanted to say thx for the great answer! sorry for the delay-just finished a big project and wanted to tie up these loose ends. i tried both methods: 1. using the "pass" statement; 2. removing the "def __init__(self):" function altogether. both worked, so i just left it off permanently. – user13318679 Aug 17 '22 at 18:45