Why can't I call a private method when I'm inside a public method?

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, this gives me the following error:

NameError: global name '_MyClass__private' is not defined

What am I doing wrong?

+5
source share
2 answers

You need to self:

self.__private()

Classes in python get used to it if you come with C # / C ++ / Java, as if it looks like you. This probably destroys the “pythonic” way of formulating things, but you can think of it this way (it helped me):

, self , . "Private" , , self.__private().

, , , . python, , , .

, self . (, ) , , . :

def __private(randomText):
    print "Hey man! This is private!"

def public(otherRandomText):
    otherRandomText.__private()
    print "I don't care if you see this!"

, , . (self ).

pythonistas / ?

+20

as is MyCalls.__ private, :

class MyClass:
    def __private(self):
        print "Hey man! This is private!"

    def public(self):
        self.__private()
        print "I don't care if you see this!"

if __name__ == '__main__':
    x = MyClass()
    x.public()
+3

All Articles