Python“专用"函数编码约定 [英] Python "private" function coding convention

查看:105
本文介绍了Python“专用"函数编码约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写python模块及其中的函数时,我有一些公开"函数应该暴露给外部人员,而其他一些私有"函数则只能在本地和内部查看和使用. /p>

我了解在python中没有绝对私有函数.但是,区分公共"功能和私人"功能的最佳,最简洁或最常用的风格是什么?

我列出了一些我知道的样式:

  1. 在模块文件中使用__all__表示其公共"功能(

人们还有其他想法或约定吗?

非常感谢!

解决方案

来自Python的

由于类私有成员有一个有效的用例(即避免名称与子类定义的名称发生名称冲突),因此对这种称为名称处理的机制的支持有限.形式为__spam的任何标识符(至少两个前导下划线,至多一个下划线)在文本上被_classname__spam替换,其中classname是当前的类名,其中前导下划线被去除.只要不存在标识符的语法位置,就可以进行这种修饰,只要它出现在类的定义之内即可.

When writing a python module and functions in it, I have some "public" functions that are supposed to be exposed to outsiders, but some other "private" functions that are only supposed to be seen and used locally and internally.

I understand in python there is no absolute private functions. But what is the best, most neat, or most used style to distinguish "public" functions and "private" functions?

I list some of the styles I know:

  1. use __all__ in module file to indicate its "public" functions (What's the python __all__ module level variable for?)
  2. use underscore at the beginning of name of "private" functions

Is there any other idea or convention that people use?

Thank you very much!

解决方案

From Python's Class module documentation:

Private" instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

这篇关于Python“专用"函数编码约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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