所以我知道这个问题已经被问过很多次了,但我似乎不能 了解我需要什么 放入 init 定义。当我调用 open_ssh_tunnel 函数时。错误 类型错误:open_ssh_tunnel() 缺少 1 个必需的位置参数:“self”。 任何帮助将不胜感激。
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()
答案 0 :(得分:0)
根据您在 open_ssh_tunnel
中的代码,您似乎使用了 3 个实例变量 ssh_host
、ssh_username
和 ssh_password
。这些实例变量应在您的 __init__
方法中定义,因为您使用 self
调用它们。类似的东西:
class SSHExample:
def __init__(self):
self.ssh_host = "<insert ssh host value>"
self.ssh_username = "<insert username value>"
self.ssh_password = "<insert password value>"
更有可能的是,您必须在初始化对象时传入这 3 个值,因为主机、用户名和密码并不总是相同的值。所以 __init__
方法看起来像:
def __init__(self, host, username, password):
self.ssh_host = host
self.ssh_username = username
self.ssh_password = password
这三个实例变量随后将在您定义的 open_ssh_tunnel
方法中使用。
self
是一个实例变量本身,它引用您已初始化的对象。您只能使用它在类的其他方法中调用对象的其他实例变量。使用上面的第二个 __init__
对其进行初始化的示例如下所示:
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"