Python入门教程第67篇 私有函数

Posted 不剪发的Tony老师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python入门教程第67篇 私有函数相关的知识,希望对你有一定的参考价值。

本篇我们学习如何使用 __all__ 变量定义模块中的私有函数(private function)。

使用下划线前缀定义私有函数

假如存在以下 mail.py 模块,其中包含两个函数 send() 和 attach_file()。

def send(email, message):
    print(f'Sending "message" to email')

def attach_file(filename):
    print(f'Attach filename to the message')

我们只想将 send() 函数暴露给其他模块。或者说,我们想要将 attach_file() 定义为私有函数,mail 模块之外的代码无法访问到该函数。作为演示,我们只是在这两个函数中打印了一些信息。

如果其他模式使用了下面的导入语句:

from mail import *

我们可以在函数名前面加上一个下划线(_),表示定义私有函数。例如:

def send(email, message):
    print(f'Sending "message" to email')

def _attach_file(filename):
    print(f'Attach filename to the message')

在其他文件中,我们可以使用 import 语句导入 mail 模块,但是只能看到 send() 函数:

from mail import *


send('test@example.com','Hello')

也就是说,我们不能在其他模块中访问 _attach_file() 函数;否则,将会返回错误。

使用 __all__ 变量定义私有函数

将 attach_file() 函数定义为私有函数的另一个放就是使用 __all__ 变量。这种方法定义的私有函数不需要使用下划线前缀。

__all__ 变量指定了一个在其他模块中可见的函数(变量以及其他对象)列表。也就是说,不在该变量中的函数就是私有函数。

以下示例在 mail 模块中使用 __all__ 变量将 send() 定义为公有函数,同时将 attach_file() 定义为私有函数:

# mail.py

__all__ = ['send']

def send(email, message):
    print(f'Sending "message" to email')

def attach_file(filename):
    print(f'Attach filename to the message')

同样,main.py 模块中无法访问 attach_file() 函数:

# main.py

from mail import *


send('test@example.com','Hello')

在前面的模块教程中我们提醒过,import * 并不是一个好的习惯,可能会导致一些问题。不过,我们仍然可用在包中使用这种语法。

首先,创建一个包含 __init__.py 文件的包 mail,然后在其中创建一个 email.py 模块:

├── mail
|  ├── email.py
|  └── __init__.py
└── main.py

其次,将以下代码写入 email.py 文件:

# email.py

__all__ = ['send']


def send(email, message):
    print(f'Sending "message" to email')


def attach_file(filename):
    print(f'Attach filename to the message')

最后,在 __init__.py 文件中使用 import * 语句将 send() 函数添加到t __all__ 变量中:

from .email import * 

__all__ = email.__all__

这样一来,mail 包只对外暴露了 email.__all__ 变量中的 send() 函数,隐藏了 attach_file() 函数。

在 main.py 文件中可用使用以下代码导入 mail 包并使用 send() 函数:

# main.py

import mail


mail.send('test@example.com','Hello')

或者也可以直接导入 mail 包中的 send() 函数:

# main.py

from mail import send


send('test@example.com','Hello')

总结

Python 定义私有函数的步骤如下:

  • 首先,创建一个包含 __init__.py 文件的包。
  • 其次,在模块的 __all__ 变量中排除该函数。
  • 最后,在 __init__.py 文件中导入模块中的对象,并且通过包的 __all__ 变量暴露公有函数。

以上是关于Python入门教程第67篇 私有函数的主要内容,如果未能解决你的问题,请参考以下文章

python进阶第1篇 函数入门

Python入门教程第31篇 sorted()函数

Python入门教程第38篇 filter()函数

Python入门教程第23篇 函数之默认参数

Python入门教程第74篇 文件目录

Python入门教程第39篇 reduce()函数