为什么当我在公共方法中时不能调用私有方法?
我有以下代码:
class MyClass:
def __private(self):
print "Hey man! This is private!"
def public(self):
__private()
print "I don't care if you see this!"
if __name__ == '__main__':
x = MyClass()
x.public()
但是它给了我以下错误:
NameError:未定义全局名称'_MyClass__private'
我做错了什么?
I have the following code:
class MyClass:
def __private(self):
print "Hey man! This is private!"
def public(self):
__private()
print "I don't care if you see this!"
if __name__ == '__main__':
x = MyClass()
x.public()
However it gives me the following error:
NameError: global name '_MyClass__private' is not defined
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你需要 self:
如果你来自 C#/C++/Java,Python 中的类需要习惯,就像你看起来的那样。这可能是在破坏“Pythonic”的措辞方式,但你可以这样想(它帮助了我):
每个类定义了一个命名空间,从其自身内部定义为 self ,从外部定义为该类的实例的名称。带有两个下划线的“私有”内容会被破坏,因此从外部您必须通过特殊名称来调用它,但从内部您可以简单地使用
self.__private()
。正如 Joe 在他的评论中提到的那样,普通的私有变量通常只是用一个下划线命名,双下划线会破坏它,因此继承可以在子类中没有名称冲突的情况下工作。 python 中没有强制执行隐私,这纯粹是约定俗成的规定,即您不能从类外部使用私有变量。
正如 Thomas 提到的,
self
也是一种约定。对于任何方法(声明为类的一部分的函数),调用该方法的实例是传入的第一个参数。您可以轻松地执行此操作:但是,如果您这样做,则需要逻辑和良好的编程精神风格将永远困扰您和您的后代。 (
self
更可取)。任何 pythonistas 希望纠正/进一步解释吗?
You need
self
:Classes in python take getting used to if you're coming from C#/C++/Java, like it looks like you are. This is probably butchering the "pythonic" way of wording things, but you can think about it like this (it helped me out):
Each class defines a namespace defined from within itself as
self
and from without by the name of an instance of that class. "Private" things with two underscores get mangled so that from without you have to call it by a special name, but from within you can simply useself.__private()
.As Joe mentioned in his comment normal private variables are typically just named with a single underscore, the double underscore mangles it so inheritance can work without name clashes in sub-classes. There's no enforcement of privacy in python, it's purely convention that says you can't use a private variable from outside the class.
As Thomas mentioned,
self
is also a convention. For any method (a function declared as part of a class) the instance that the method is being called on is the first parameter passed in. You could just as easily do this:However, if you do that the spirits of logic and good programming style will haunt you and your descendants for all eternity. (
self
is much preferable).Any pythonistas wish to correct/further-explain?
您的代码正在尝试调用静态函数 MyCalls.__private,您想要执行以下操作:
Your code as is is trying to call a static function MyCalls.__private, you want to do this: