Function variable scope in python

前端 未结 3 718
无人共我
无人共我 2021-01-29 01:04

let\'s say we have two functions:

def ftpConnect(): 
    ftp = FTP(\'server\')
    ftp.login()
    ftp.cwd(\'/path\')

def getFileList():
    ftpConnect()
    fi         


        
3条回答
  •  盖世英雄少女心
    2021-01-29 01:16

    Functions can return values. Return values are cool!

    Return ftp from ftpConnect():

    def ftpConnect(): 
        ftp = FTP('server')
        ftp.login()
        ftp.cwd('/path')
        # return the value of `ftp` to the caller
        return ftp
    
    def getFileList():
        # assign the return value of `ftpConnect` to a new local variable
        ftp = ftpConnect()
        files = ftp.nlst()
        print(ftp.nlst())
    

    You may also want to look in to object-oriented programming techniques; define a class that handles all your FTP-related operations, and store the FTP server connection as an attribute of the instance.

提交回复
热议问题