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?
An object user can use the public methods, but can't directly access private instance variables. You can make methods private too. Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.
Yes, you're right.it was for public static void main(String args[]) but for the non-static ones i dont need to use the object of the class.it doesnt give an error if i call it simply by the method name.
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.
You need self
:
self.__private()
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 use self.__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:
def __private(randomText):
print "Hey man! This is private!"
def public(otherRandomText):
otherRandomText.__private()
print "I don't care if you see 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With