2014-04-02 28 views
-1

我知道python中的所有东西都是公共的,我们只是将这些变量用双下划线作为私有变量来处理,但我们可以通过其他方式在类之外访问这些变量。但是当我测试下面的代码时遇到了一些问题。关于python私有方法的一个奇怪的问题

class SA: 
    def __myPrivate(self,name): 
     return 'private'+name 
    def _myProtected(self): 
     self.name = 'protected name'  
    def setName(self,name): 
     self.name = self.__myPrivate(name) 
    def getName(self): 
     return self.name 
    def printf(self): 
     print self.name 

si = SA() 
print si._SA_myPrivate('niutou') 

的例外是:

print si._SA_myPrivate('niutou') 
AttributeError: SA instance has no attribute '_SA_myPrivate' 

为什么呢?请帮我解决这个问题。谢谢!

是的,我意识到我犯了一个低级错误!它应该是si。 SA _myPrivate( '牛头')不si._SA_myPrivate( '牛头')

+3

阅读文档的第二段:https://docs.python.org/3/tutorial/classes.html#private-variables – Blender

+0

可能因为您从不定义'_SA_myPrivate'属性。 –

回答

3

你想

>>> print si._SA__myPrivate('niutou') 
privateniutou 

注意双_。魔术替换保留了这一点,只有在该属性被转换时才附加_ + classname

+0

我不理解你,你能详细解释一下吗?谢谢! – user3418149

+0

作为评分最高的评论指出:阅读教程:https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references – metatoaster