python类不能提供\u Secretive\u xxx()函数,为什么?

2024-09-30 08:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试是否可以调用python类的私有函数,我在ipython中尝试了:

In [14]: class C:
   ....:     def __my(s):
   ....:         print "hello"
   ....:       

In [15]: print C
__main__.C

In [16]: obj=C()

In [17]: obj._Secretive__my
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-c68d82fedeb4> in <module>()
----> 1 obj._Secretive__my

AttributeError: C instance has no attribute '_Secretive__my'
In [18]: obj._Secretive__my()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-18-ab4a9965f82a> in <module>()
----> 1 obj._Secretive__my()

好吧,看来我不能统计或调用它,对吗?我哪里出错了?在


Tags: inobjmostinputmyipythoncalllast
3条回答

双下划线前缀名得到mangled using the class name-即C,在本例中:

>>> class C:
...     def __my(self):
...         print('hello')
...         
>>> obj = C()
>>> obj._C__my()
hello

不要使用此功能来尝试并指示方法是“私有”。为此,只需使用一个下划线。名称混乱特性是为了防止在一些罕见和复杂的继承情况下发生名称冲突。在

实现名为name mangling的“私有”实例变量的方式。见文件Private Variables and Class-local References

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

试试这个:

obj._C__my
obj._C__my()

方法的名称是preceded,由_和类名(C):

>>> class C:
...   def __my(self):
...     print "hello"
... 
>>> obj = C()
>>> dir(obj)
['_C__my', '__doc__', '__module__']
>>> obj._C__my()
hello

因此,您可以调用该方法,但是奇怪的命名转换应该让您三思而后行。在

相关问题 更多 >

    热门问题