You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类定义中是否必须实现def __init__(self)?相关问题解答

问题解答

1. 空__init__引发的缩进错误

Python规定函数定义后必须紧跟缩进的代码块,哪怕函数内部什么逻辑都没有。你取消注释__init__后,直接写了def __init__(self):却没有后续缩进代码,所以触发了IndentationError。解决办法很简单,给空方法加个pass占位即可:

def __init__(self):
    pass

2. __init__不是必须定义的

当你没手动写__init__时,Python会自动给类生成一个默认的空构造方法,它的作用就是让你能正常创建类的实例,不会影响其他方法的运行。如果你的类不需要在实例化时初始化属性,完全可以不写__init__,这是合法且正常的写法。

3. 未定义__init__时self仍正常工作的原因

self代表类的实例对象,不管有没有定义__init__,只要通过实例调用类的方法,Python都会自动把这个实例作为第一个参数传给方法的self参数。你在sshCLIENT里给self.sshSESS赋值,本质是给当前实例添加了一个属性,后续其他方法通过self访问这个属性完全没问题,这是Python类的正常行为,不用担忧。

代码优化建议

  1. 将SSH客户端初始化移到__init__中:创建实例时自动完成sshSESS的初始化,无需手动调用sshCLIENT,逻辑更连贯:
class SSHCONN():
    '''paramiko connection object class for SSH logins'''
    
    def __init__(self):
        self.sshSESS = paramiko.SSHClient()
        self.sshSESS.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1. 修复代码笔误:CONNECT方法最后一个except块里的selfsshSESS.close()少了点,应该是self.sshSESS.close()。
  2. SFTP方法优化:SFTPOPEN里可以把sftp实例存到self上,后续SFTPPUT和SFTPCLOSE不用重复调用open_sftp(),避免重复创建连接。

修正后的完整代码示例

import paramiko
import os
import sys

# 假设LogDrop是自定义日志函数
def LogDrop(msg):
    print(msg)

class SSHCONN():  #paramiko connection object class for SSH logins
    '''paramiko connection object class for SSH logins'''
    
    def __init__(self):
        self.sshSESS = paramiko.SSHClient()  #初始化SSH会话对象
        self.sshSESS.set_missing_host_key_policy(paramiko.AutoAddPolicy())  #自动添加主机密钥
            
    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}\'')
            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('...')
            self.sshSESS.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.sftp = 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:
            filename = os.path.basename(file)
            remote_path = f"{strRmtSubDir.rstrip('/')}/{filename}"
            LogDrop(f'Transferring file {filename} to server: {IP}')
            LogDrop(f'at remote location: {remote_path}')
            self.sftp.put(file, remote_path)
        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.sftp.close()
            LogDrop(f'SFTP Channel successfully closed to: {IP}')
        except:
            LogDrop(f'SFTP Channel failed to close to: {IP}')

内容的提问来源于stack exchange,提问作者user13318679

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:15:28