0

So i know this question has been asked many times but i cant seem to understand what i need to put in the init def. When i am calling the open_ssh_tunnel function. The error TypeError: open_ssh_tunnel() missing 1 required positional argument: 'self'. Any help would be much appreciated.

def __init__(self):
    ???

def open_ssh_tunnel(self, verbose=False):
    """Open an SSH tunnel and connect using a username and password.
    :param verbose: Set to True to show logging
    :return tunnel: Global SSH tunnel connection
    """
    if verbose:
        sshtunnel.DEFAULT_LOGLEVEL = logging.DEBUG

    global tunnel
    tunnel = SSHTunnelForwarder(
        (self.ssh_host, 22),
        ssh_username= self.ssh_username,
        ssh_password= self.ssh_password,
        remote_bind_address=('127.0.0.1', 3306)
    )
    tunnel.start()
Voldrakon
  • 1
  • 1
  • Does this answer your question? [What \_\_init\_\_ and self do in Python?](https://stackoverflow.com/questions/625083/what-init-and-self-do-in-python) – Flair Jul 12 '21 at 18:41
  • I suggest you explore basic oop before trying to learn 'chunks' of knowledge that will make your work even harder. – Max Shouman Jul 12 '21 at 19:41

1 Answers1

0

Based on your code in open_ssh_tunnel, it looks like you are using 3 instance variables ssh_host, ssh_username and ssh_password. These instance variables should be defined in your __init__ method since you are calling them using self. Something like:

class SSHExample:
  def __init__(self):
    self.ssh_host = "<insert ssh host value>"
    self.ssh_username = "<insert username value>"
    self.ssh_password = "<insert password value>"

More likely, you will have to pass in these 3 values when you initialize the object, since the host, username, and password will not always be the same values. So the __init__ method would look like:

def __init__(self, host, username, password):
  self.ssh_host = host
  self.ssh_username = username
  self.ssh_password = password

These three instance variables would then be used in the open_ssh_tunnel method you have defined.

self is an instance variable itself that refers to the object that you have initialized. You would only use this to call the object's other instance variables within the other methods in the class. An example of initializing this with the second __init__ above would look like:

ssh_obj = SSHExample('fake_host', 'fake_user', 'fake_pass')
print(ssh_obj.ssh_host) # prints "fake_host"
print(ssh_obj.ssh_username) # prints "fake_user"