Python Private

Python Private




๐Ÿ”ž ALL INFORMATION CLICK HERE ๐Ÿ‘ˆ๐Ÿป๐Ÿ‘ˆ๐Ÿป๐Ÿ‘ˆ๐Ÿป

































Python Private

Sign up or log in to customize your list.

more stack exchange communities

company blog


Stack Overflow for Teams
โ€“ Start collaborating and sharing organizational knowledge.



Create a free Team
Why Teams?



Asked
12 years, 10 months ago


32.9k 12 12 gold badges 93 93 silver badges 124 124 bronze badges


28.6k 47 47 gold badges 138 138 silver badges 186 186 bronze badges




Highest score (default)


Trending (recent votes count more)


Date modified (newest first)


Date created (oldest first)




2,720 28 28 silver badges 27 27 bronze badges


29.7k 5 5 gold badges 47 47 silver badges 64 64 bronze badges


24.2k 8 8 gold badges 51 51 silver badges 71 71 bronze badges


9,046 4 4 gold badges 35 35 silver badges 41 41 bronze badges


1,876 1 1 gold badge 13 13 silver badges 8 8 bronze badges


810 5 5 silver badges 11 11 bronze badges


1,579 1 1 gold badge 15 15 silver badges 19 19 bronze badges


23.3k 18 18 gold badges 105 105 silver badges 142 142 bronze badges


1,058 1 1 gold badge 11 11 silver badges 19 19 bronze badges


22.3k 4 4 gold badges 40 40 silver badges 56 56 bronze badges


29.1k 11 11 gold badges 95 95 silver badges 100 100 bronze badges


376k 78 78 gold badges 502 502 silver badges 771 771 bronze badges


1,042 2 2 gold badges 12 12 silver badges 30 30 bronze badges


89 1 1 silver badge 1 1 bronze badge


2,418 1 1 gold badge 16 16 silver badges 18 18 bronze badges


731 9 9 silver badges 11 11 bronze badges


185 1 1 silver badge 1 1 bronze badge


24.1k 4 4 gold badges 39 39 silver badges 38 38 bronze badges


343 3 3 silver badges 10 10 bronze badges


1,208 14 14 silver badges 26 26 bronze badges


Highly active question . Earn 10 reputation (not counting the association bonus ) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.



Stack Overflow

Questions
Help



Products

Teams
Advertising
Collectives
Talent



Company

About
Press
Work Here
Legal
Privacy Policy
Terms of Service
Contact Us
Cookie Settings
Cookie Policy



Stack Exchange Network



Technology




Culture & recreation




Life & arts




Science




Professional




Business





API





Data






Accept all cookies



Customize settings


Find centralized, trusted content and collaborate around the technologies you use most.
Connect and share knowledge within a single location that is structured and easy to search.
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.
If thatโ€™s true, then any object of class Simple can just change the value of variable s outside of the class.
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?
Trending sort is based off of the default sorting method โ€” by highest score โ€” but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
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 .
Private variables in python is more or less a hack: the interpreter intentionally renames the variable.
Now, if you try to access __var outside the class definition, it will fail:
But you can easily get away with this:
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
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 __.
Python does not have any private variables like C++ or Java does. You could access any member variable at any time if wanted, too. However, you don't need private variables in Python, because in Python it is not bad to expose your classes member variables. If you have the need to encapsulate a member variable, you can do this by using "@property" later on without breaking existing client code.
In python the single underscore "_" is used to indicate, that a method or variable is not considered as part of the public api of a class and that this part of the api could change between different versions. You can use these methods/variables, but your code could break, if you use a newer version of this class.
The double underscore "__" does not mean a "private variable". You use it to define variables which are "class local" and which can not be easily overidden by subclasses. It mangles the variables name.
self.__foobar's name is automatically mangled to self._A__foobar in class A. In class B it is mangled to self._B__foobar. So every subclass can define its own variable __foobar without overriding its parents variable(s). But nothing prevents you from accessing variables beginning with double underscores. However, name-mangling prevents you from calling this variables /methods incidentally.
I strongly recommend you watch Raymond Hettinger's Python's class development toolkit from Pycon 2013, which gives a good example why and how you should use @property and "__"-instance variables.
If you have exposed public variables and you have the need to encapsulate them, then you can use @property. Therefore you can start with the simplest solution possible. You can leave member variables public unless you have a concrete reason to not do so. Here is an example:
There is a variation of private variables in the underscore convention.
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
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:
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
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.
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.
"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 .
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?
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.
Sorry guys for "resurrecting" the thread, but, I hope this will help someone:
In Python3 if you just want to "encapsulate" the class attributes, like in Java, you can just do the same thing like this:
Note that: print(ss.__s) will throw an error.
In practice, Python3 will obfuscate the global attribute name. Turning this like a "private" attribute, like in Java. The attribute's name is still global, but in an inaccessible way, like a private attribute in other languages.
But don't be afraid of it. It doesn't matter. It does the job too. ;)
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.
About sources (to change the access rights and thus bypass language encapsulation like java or C ++):
You don't always have the sources and EVEN if you do, the sources are managed by a system that only allows certain programmers to access a source (in a professional context). Often, every programmer is responsible for certain classes and therefore knows what he can and cannot do. The source manager also locks the sources being modified and of course, manages the access rights of programmers.
So i trust more in software than in human, by experience. So convention is good but MULTIPLE protections are better, like access management (real private variable) + sources management.
So Iโ€™m new to Python but I have a background in C# and JavaScript. Python feels like a mix of the two in terms of features. JavaScript also struggles in this area and the way around it here, is to create a closure. This prevents access to data you donโ€™t want to expose by returning a different object.
Here's how I handle Python3 class fields:
I access the __private_variable with two underscores only inside MyClass methods.
I do read access of the public_read_variable_ with one underscore
outside the class, but never modify the variable:
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo ยฉ 2022 Stack Exchange Inc; user contributions licensed under CC BY-SA . revย 2022.9.6.42960


By clicking โ€œAccept all cookiesโ€, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .



Sign up or log in to customize your list.

more stack exchange communities

company blog


Stack Overflow for Teams
โ€“ Start collaborating and sharing organizational knowledge.



Create a free Team
Why Teams?



Asked
9 years, 2 months ago


30.4k 21 21 gold badges 102 102 silver badges 124 124 bronze badges


3,372 3 3 gold badges 28 28 silver badges 49 49 bronze badges




Highest score (default)


Trending (recent votes count more)


Date modified (newest first)


Date created (oldest first)




30.4k 21 21 gold badges 102 102 silver badges 124 124 bronze badges


236k 55 55 gold badges 441 441 silver badges 495 495 bronze badges


30.4k 21 21 gold badges 102 102 silver badges 124 124 bronze badges


25.2k 5 5 gold badges 47 47 silver badges 61 61 bronze badges


30.4k 21 21 gold badges 102 102 silver badges 124 124 bronze badges


582 1 1 gold badge 5 5 silver badges 13 13 bronze badges


285k 50 50 gold badges 357 357 silver badges 498 498 bronze badges


30.4k 21 21 gold badges 102 102 silver badges 124 124 bronze badges


24k 4 4 gold badges 53 53 silver badges 86 86 bronze badges


Stack Overflow

Questions
Help



Products

Teams
Advertising
Collectives
Talent



Company

About
Press

Naked Lil
Lesbian Face Sit
Outdoor Screens

Report Page