我建立了一个看起来像这样的图书馆:
class AXISSetGet(object):
def SSH_Start(self):
cfg = yaml.load(open(config_file_path))
HOST = cfg['afo_axis_host']
PORT = cfg['afo_axis_port']
USERNAME = cfg['afo_axis_username']
PASSWORD = cfg['afo_axis_password']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=HOST, port=PORT, username=USERNAME, password=PASSWORD)
def Get_File (self,filename):
# rest of the function
该类的所有其他函数都需要SSH_Start()函数。 我试图在声明该类之前编写SSH_Start(),但是它不起作用。
有人可以帮我吗? 谢谢!
答案 0 :(得分:1)
您可以使用self来访问同一类的函数,我想这就是您想要的吗?
class AXISSetGet(object):
def SSH_Start(self):
cfg = yaml.load(open(config_file_path))
HOST = cfg['afo_axis_host']
PORT = cfg['afo_axis_port']
USERNAME = cfg['afo_axis_username']
PASSWORD = cfg['afo_axis_password']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=HOST, port=PORT, username=USERNAME,password=PASSWORD)
def Get_File (self,filename):
self.SSH_Start()
答案 1 :(得分:1)
添加SSH客户端作为实例属性,然后可以通过任何方法使用它。从您现有的代码来看,我不希望您多次调用SSH_Start方法,您只需要打开SSH连接即可。尝试类似的东西:
class AXISSetGet(object):
def __init__(self):
self.SSH_Start() # Call it here to ensure the connection has been made before it's needed.
def SSH_Start(self):
# config stuff
ssh = paramiko.SSHClient()
# ...
self.ssh = ssh
def Get_File (self,filename):
self.ssh.use_client_here(...)
我很想在这里看看properties。这样,您第一次尝试使用客户端时,它将创建一个并进行连接,然后将现有客户端用于后续调用。像这样:
class AXISSetGet(object):
def __init__(self):
self._ssh = None
@property
def ssh(self):
# if this is the first time the connection has been needed, create it
if not self._ssh:
# config stuff
ssh = paramiko.SSHClient()
# ...
self._ssh = ssh
# and then just return the existing one
return self._ssh
def Get_File (self,filename):
self.ssh.use_client_here(...)
作为旁注,请通读PEP8,以获取有关命名约定和格式的准则。它不会改变代码的行为,但会使其他人更容易阅读和理解。