私人成员在python [英] private members in python

查看:120
本文介绍了私人成员在python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使Python中的方法和数据成员为私有?或者不支持私人成员?

How can I make methods and data members private in Python? Or doesn't python support private members?

推荐答案


9.6。私有变量

私有实例变量
无法访问,除非从
内部访问一个对象, t存在于Python中。
然而,有一个约定是
后跟大多数Python代码:一个名称
前缀一个下划线(例如
_spam)应该被视为一个非公开部分API(无论它
是一个函数,一个方法或一个数据
成员)。它应该被认为是一个
的实现细节,并受到
的更改,恕不另行通知。

"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.

由于
有一个有效的用例类私有成员(即避免
名称冲突的名称由子类定义的名称
),有
有限支持这种机制,
称为名称调整。 __spam(至少两个
前导下划线,最多一个
尾部下划线)的任何标识符
在文本上用 _classname__spam ,其中
classname是当前类名
,带有前导下划线。
只要在类的定义中出现
,这个修改不考虑

标识符的句法位置。

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.

因此,例如

class Test:
    def __private_symbol(self):
        pass
    def normal_symbol(self):
        pass

print dir(Test)

将输出:

['_Test__private_symbol', 
'__doc__', 
'__module__', 
'normal_symbol']

__ private_symbol 应该被认为是一个私有方法,但它仍然可以通过 _Test__private_symbol 访问。

__private_symbol should be considered a private method, but it would still be accessible through _Test__private_symbol.

这篇关于私人成员在python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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