我在尝试是否可以调用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()
好吧,看来我不能统计或调用它,对吗?我哪里出错了?在
双下划线前缀名得到mangled using the class name-即
C
,在本例中:不要使用此功能来尝试并指示方法是“私有”。为此,只需使用一个下划线。名称混乱特性是为了防止在一些罕见和复杂的继承情况下发生名称冲突。在
实现名为name mangling的“私有”实例变量的方式。见文件Private Variables and Class-local References
试试这个:
方法的名称是preceded,由
_
和类名(C
):因此,您可以调用该方法,但是奇怪的命名转换应该让您三思而后行。在
相关问题 更多 >
编程相关推荐