Python 中的私有成员 [英] Private members in Python

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

问题描述

如何在 Python 中将方法和数据成员设为私有?还是 Python 不支持私有成员?

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

推荐答案

9.6.私有变量

私有"实例变量除了从内部无法访问一个对象,在 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天全站免登陆