带有__的Python'hide'方法 [英] Python 'hide' methods with __

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

问题描述

今天我看到-python将_$CLASSNAME$添加到名称为__的方法中.

Today I see that - python add _$CLASSNAME$ to methods with name with __.

简单的例子:

>>> class A:  
...     def a(self):  
...         self.b()  
...     def b(self):  
...         print('A.b')  
...           
>>> class B(A):  
...     def b(self):  
...         print('B.b')  
...           
>>> B().a()  
B.b

可以,但是:

>>> class A:  
...     def a(self):  
...         self.__b()  
...     def __b(self):  
...         print('A.b')  
...           
>>> class B(A):  
...     def __b(self):  
...         print('B.b')  
...           
>>> B().a()  
A.b

为什么?我不知道,所以我把它弄脏了.在这里:

Why? I don't know, so I dir'ed it. Here it is:

>>> print([fn for fn in dir(B) if fn[-2:] != '__'])
['_A__b', '_B__b', 'a']

为什么python这样做?有办法绕过吗?

Why python do that? Is there way to bypass that?

推荐答案

这称为名称修饰,其目的是防止与父类和子类发生意外的名称冲突.您不能(也不应该,很多完美的代码使用它)禁用它.您可以规避它,但是您也不应该这样做(这非常丑陋,可以避免,并且当您需要访问它时,您首先不应该允许名称篡改).只需对要在类中任何地方但要在类内立即使用的私有函数使用单个下划线.

It's called name mangling and done to prevent accidental name collisions with parent and child classes. You cannot (and should not, a lot of perfectly fine code uses it) disable it. You can circumvent it, but you should not do that either (it's extremely ugly, you can avoid it, and when you need access to it you shouldn't permit name mangling in the first place). Just use a single underscore for private functions you want to use anywhere but immediately inside the class.

请参见教程,但忽略对此引用的任何引用一个私有"变量.除非您在C ++/Java/C#/中使用private,否则这不是它的用途....在子类中隐藏了private变量(与子类可见的protected相对)的含义.即便如此,这还是一个有缺陷的类比.

See the tutorial but ignore any reference to this denoting a "private" variable. That's not what it's used for unless you use private in the C++/Java/C#/... sense of private variables (as opposed to protected which are visible to child classes) being hidden from child classes. Even then it's a flawed analogy.

这篇关于带有__的Python'hide'方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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