python中的函数变量范围 [英] Function variable scope in python

查看:50
本文介绍了python中的函数变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个功能:

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

def getFileList():
    ftpConnect()
    files = ftp.nlst()
    print(files)

如果我调用getFileList()函数,它将不起作用,因为它不知道ftp var.

If I call the getFileList() function it won't work because it doesn't know the ftp var.

我知道,如果我将ftpConnect()函数中的ftp变量声明为全局变量,它将起作用,但是我想知道是否有更好/更优雅的方法.

I know that if I declare the ftp variable inside ftpConnect() function as global it will work, but I was wondering if there is a better / more elegant way of doing it.

推荐答案

在我看来,最优雅的解决方案是制作一个FTP类,该类将 ftp 变量作为私有属性.

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()

这篇关于python中的函数变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆