I'm coming from the Java world and reading Bruce Eckels' Python 3 Patterns, Recipes and Idioms.

While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there.

So for example:

class Simple:
    def __init__(self1, str):
        print("inside the simple constructor")
        self1.s = str
    def show(self1):
        print(self1.s)
    def showMsg (self, msg):
        print (msg + ':', self.show())

If that’s true, then any object of class Simple can just change the value of variable s outside of the class.

For example:

if __name__ == "__main__":
    x = Simple("constructor argument")
    x.s = "test15" # this changes the value
    x.show()
    x.showMsg("A message")

In Java, we have been taught about public/private/protected variables. Those keywords make sense because at times you want variables in a class to which no one outside the class has access to.

Why is that not required in Python?

share|improve this question
10  
You meant instance variables, not class variables, right? – PaulMcG Nov 13 '09 at 9:07
9  
You should check properties: docs.python.org/library/functions.html#property. Just use the getter and your variable will be protected. – rubik Jul 17 '11 at 6:05
21  
why do you use self1, btw? – njzk2 Feb 25 '14 at 18:22
7  
Again, why do you use self1? – noɥʇʎԀʎzɐɹƆ Nov 5 '16 at 19:27
10  
@SumukhBarve the article is private. How ironic. – noɥʇʎԀʎzɐɹƆ Nov 5 '16 at 19:30

10 Answers 10

up vote 702 down vote accepted

It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.

If you want to emulate private variables for some reason, you can always use the __ prefix from PEP 8. Python mangles the names of variables like __foo so that they're not easily visible to code outside the class that contains them (although you can get around it if you're determined enough, just like you can get around Java's protections if you work at it).

By the same convention, the _ prefix means stay away even if you're not technically prevented from doing so. You don't play around with another class's variables that look like __foo or _bar.

share|improve this answer
8  
That makes sense. However, I dont think there is any way in java to access private variables outside the class (except actually changing the source of the class ofcourse). Is there? – Omnipresent Oct 29 '09 at 2:06
7  
@David - the presumption is that we're all adults here. Don't break things that you can't fix! In this case, that means that you shouldn't mess around with those private members like __foo or _bar. Again, in practice, that's just not done without an extremely good reason. It might not be theoretically pure, but I've never once seen a real-world situation where it was a problem. – Kirk Strauser Oct 29 '09 at 2:12
93  
I tend to prefer the python way, but I don't think the java way is as pointless as you make out. Declaring something private quickly tells someone reading the code something very useful: this field is only ever modified inside this class. – Ned Nov 13 '09 at 9:24
48  
@Omnipresent, you can using reflection. – rapadura Mar 22 '11 at 12:49
9  
@dVaffection "Yes, a Jedi’s strength flows from the Force. But beware of the dark side. Anger, fear, aggression; the dark side of the Force are they. Easily they flow, quick to join you in a fight. If once you start down the dark path, forever will it dominate your destiny, consume you it will, as it did Obi-Wan’s apprentice." – m93a Nov 7 '13 at 19:55

Sorry guys for "resuscitate" the tread, but, I hope this helps someone:

In Python3 if you just want to "encapsulate" the class attributes, like in Java, you can just do same thing like this:

class Simple:
def __init__(self, str):
    print("inside the simple constructor")
    self.__s = str

def show(self):
    print(self.__s)

def showMsg(self, msg):
    print(msg + ':', self.show())

To instantiate this do:

ss = Simple("lol")
ss.show()

Note that: print(ss.__s) will trow an error.

In pratice Python3 will obfscate the global attribute name. Turning this like an "private" attribute, like in Java. The attribute name still global, but in a inacessible way, like a private attribute in other languegaes.

But dont be afraid about this. it doens matter. It do the job too. ;)

share|improve this answer

Private variables in python is more or less a hack: the interpreter intentionally renames the variable.

class A:
    def __init__(self):
        self.__var = 123
    def printVar(self):
        print self.__var

Now, if you try to access __var outside the class definition, it will fail:

 >>>x = A()
 >>>x.__var # this will return error: "A has no attribute __var"

 >>>x.printVar() # this gives back 123

But you can easily get away with this:

 >>>x.__dict__ # this will show everything that is contained in object x
               # which in this case is something like {'_A__var' : 123}

 >>>x._A__var = 456 # you now know the masked name of private variables
 >>>x.printVar() # this gives back 456

You probably know that methods in OOP are invoked like this: x.printVar() => A.printVar(x), if A.printVar() can access some field in x, this field can also be accessed outside A.printVar()...after all, functions are created for reusability, there is no special power given to the statements inside.

The game is different when there is a compiler involved (privacy is a compiler level concept). It know about class definition with access control modifiers so it can error out if the rules are not being followed at compile time

share|improve this answer
    
in short, this is not encapsulation – watashiSHUN Sep 26 '15 at 22:11
2  
I wonder if PHP has something similar with its goofy private variables - since private variables don't really make sense in interpreted language - I mean what optimization can it do knowing x variable is private, if it is not compiled? – NoBugs Dec 24 '15 at 5:14
1  
How can we randomize the pattern of private variables? – crisron Feb 7 '16 at 5:29
    
@crisron same question – IanS Feb 17 '16 at 10:47
    
Using self.__dic__ = {} disallows the use of __str__ method. Is there any work around to use __str__ in this context? – arsho May 19 '17 at 3:33

As mentioned earlier, you can indicate that a variable or method is private by prefixing it with an underscore. If you don't feel like this is enough, you can always use the property decorator. Here's an example:

    class Foo:

        def __init__(self, bar):
            self._bar = bar

        @property
        def bar(self):
            """Getter for '_bar'."""
            return self._bar

This way, someone or something that references bar is actually referencing the return value of the bar function rather than the variable itself, and therefore it can be accessed but not changed. However, if someone really wanted to, they could simply use _bar and assign a new value to it. There is no surefire way to prevent someone from accessing variables and methods that you wish to hide, as has been said repeatedly. However, using property is the clearest message you can send that a variable is not to be edited. property can also be used for more complex getter/setter/deleter access paths, as explained here: https://docs.python.org/3/library/functions.html#property

share|improve this answer

As correctly mentioned by many of the comments above, let's not forget the main goal of Access Modifiers: To help users of code understand what is supposed to change and what is supposed not to. When you see a private field you don't mess around with it. So it's mostly syntactic sugar which is easily achieved in Python by the _ and __.

share|improve this answer
1  
I think this is as important a point as any. When debugging code (I know, I'm a weakling to introduce bugs), know which classes can change a member variable simplifies the debugging process. At least, if the variable is protected by some scope. A similar concept is const functions in C++. I know that member variables weren't changed in there and so I don't even look at that method as the potential cause of a bad variable setting. Although it can make subsequent development of class extensions/adding features, limiting the visibility of code makes it easier to debug. – MrMas Nov 18 '15 at 23:01

There is a variation of private variables in the underscore convention.

In [5]: class test(object):
   ...:     def __private_method(self):
   ...:         return "Boo"
   ...:     def public_method(self):
   ...:         return self.__private_method()
   ...:     

In [6]: x = test()

In [7]: x.public_method()
Out[7]: 'Boo'

In [8]: x.__private_method()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-fa17ce05d8bc> in <module>()
----> 1 x.__private_method()

AttributeError: 'test' object has no attribute '__private_method'

There are some subtle differences, but for the sake of programming pattern ideological purity, its good enough.

There are examples out there of @private decorators that more closely implement the concept, but YMMV. Arguably one could also write a class defintion that uses meta

share|improve this answer
12  
I realize this is pretty late to the party but this link shows up on google when googling the issue. This doesn't tell the whole story. __x as a variable inside class A is actually rewritten by the compiler to _A__x, it's still not fully private and can still be accessed. – Zorf Oct 13 '14 at 23:20
    
Of course, if I see a variable named _A__x, I'm not going to touch it. It could be contagious. I'll run the hell away from it. – Mateen Ulhaq Jan 9 '17 at 9:00
    
Mateen has the right idea. _A__x can be interpreted as "here be dragons" – Shayne Feb 24 '17 at 5:14

The only time I ever use private variables is when I need to do other things when writing to or reading from the variable and as such I need to force the use of a setter and/or getter.

Again this goes to culture, as already stated. I've been working on projects where reading and writing other classes variables was free-for-all. When one implementation became deprecated it took a lot longer to identify all code paths that used that function. When use of setters and getters was forced, a debug statement could easily be written to identify that the deprecated method had been called and the code path that calls it.

When you are on a project where anyone can write an extension, notifying users about deprecated methods that are to disappear in a few releases hence is vital to keep module breakage at a minimum upon upgrades.

So my answer is; if you and your colleagues maintain a simple code set then protecting class variables is not always necessary. If you are writing an extensible system then it becomes imperative when changes to the core is made that needs to be caught by all extensions using the code.

share|improve this answer

private and protected concepts are very important. But python - just a tool for prototyping and rapid development with restricted resources available for development, that is why some of protection levels are not so strict followed in python. You can use "__" in class member, it works properly, but looks not good enough - each access to such field contains these characters.

Also, you can noticed that python OOP concept is not perfect, smaltalk or ruby much closer to pure OOP concept. Even C# or Java are closer.

Python is very good tool. But it is simplified OOP language. Syntactically and conceptually simplified. The main goal of python existence is to bring to developers possibility to write easy readable code with high abstraction level in a very fast manner.

share|improve this answer
    
The rearson Private and Protected are important is that in statically compiled languages the compiler can create diirect calls to the private method, but must rely on a lookup table for public methods. Thiis simply isnt an issue with dynamic languages. Finally languages like C++ there are implications for inheritance and method resolution. Python and Ruby have very similar implementatiions of OO, so the comparison is meaningless. Smalltalk actually has no notion of public/private messages. Your free to add private as a category, but its purely advisory. – Shayne Feb 24 '17 at 5:21
    
To further my assertion. Frorm a codiing hygiene point of view, yes they are important for encapsulation, but its not necessary for it, and so the the @private (etc) decorators are more advisory than anything, but as private/public adds nothing useful to optimization in a non static language, its not implemented at a deep level like it would in a compiled language like java or c – Shayne Feb 27 '17 at 2:35

"In java, we have been taught about public/private/protected variables"

"Why is that not required in python?"

For the same reason it's not required in Java.

You're free to use -- or not use private and protected.

As a Python and Java programmer, I've found that private and protected are very, very important design concepts. But as a practical matter, in tens of thousands of lines of Java and Python, I've never actually used private or protected.

Why not?

Here's my question "protected from whom?"

Other programmers on my team? They have the source. What does protected mean when they can change it?

Other programmers on other teams? They work for the same company. They can -- with a phone call -- get the source.

Clients? It's work-for-hire programming (generally). The clients (generally) own the code.

So, who -- precisely -- am I protecting it from?

Right. The schizophrenic sociopath who refused to read the API comment blocks.

share|improve this answer
470  
The very question "protected from whom?" simply shows you don't understand what this is about. It's not about security. It's about making it easy for your IDE to know which methods are part of the public interface, and making it easy for your compiler to show that nobody is accidentally using anything else, which together make it easier for you, the programmer, to reason about your program. – Porculus Jul 23 '10 at 0:27
77  
-1: I agree with Porculus. It's not about forbidding access or hiding something, it's about implicit API documentation. Developers as well as compilers/interpreter/code-checker easily see which members are recommended to be used and which ones shouldn't get touched (or at least with care). In most cases it would be a horrible mess if all members of a class or module were public. Consider the distinction of private/protected/public members as a service, saying: "Hey, these members are important while those are used internally and probably not useful for you." – Oben Sonne Oct 6 '10 at 20:38
18  
Late to the discussion, but everything Porculus and Oben are requesting here is handled perfectly adequately by the "prefix it with an underscore" convention (and without the harm that compiler enforcement of that convention can cause) – ncoghlan Mar 2 '11 at 15:16
45  
@S.Lott Concerning your "protecting from whom" question - Those examples are silly. The real concern is data encapsulation and programming to interfaces not implementations. – hiwaylon Feb 20 '12 at 17:21
16  
@S.Lott I'm not a python guy, so I won't comment from that perspective. However as a java developer this is truly horrifying advice. -1 – dbyrne Jun 6 '14 at 14:24

Python has limited support for private identifiers, through a feature that automatically prepends the class name to any identifiers starting with two underscores. This is transparent to the programmer, for the most part, but the net effect is that any variables named this way can be used as private variables.

See here for more on that.

In general, Python's implementation of object orientation is a bit primitive compared to other languages. But I enjoy this, actually. It's a very conceptually simple implementation and fits well with the dynamic style of the language.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.