Function variable scope in python

前端 未结 3 717
无人共我
无人共我 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.

    0 讨论(0)
  • 2021-01-29 01:16

    Return ftp from ftpConnect() and assign the return value to a variable named ftp:

    def ftpConnect(): 
        ftp = FTP('server')
        ftp.login()
        ftp.cwd('/path')
        return ftp         #return ftp from here
    
    def getFileList():
        ftp = ftpConnect() # assign the returned value from the
                           # function call to a variable
        files = ftp.nlst()
        print(ftp.nlst())
    
    0 讨论(0)
  • 2021-01-29 01:17

    In my opinion, the most elegant solution would be to make a FTP-class, which would have the ftp-variable as a private attribute.

    class FTPConnection(object):
        def __init__(self, server):
            self._ftp = FTP(server)
    
        def connect(self): 
           self._ftp.login()
           self._ftp.cwd('/path')
    
    
        def getFileList():
            files = self._ftp.nlst()
            print(files)
    
    ftp = FTPConnection('server')
    ftp.connect()
    ftp.getFileList()
    
    0 讨论(0)
提交回复
热议问题