Python Public Private

Python Public Private



🔞 ALL INFORMATION CLICK HERE 👈🏻👈🏻👈🏻

































Python Public Private

Sign up or log in to customize your list.

more stack exchange communities

company blog



Sign up with email
Sign up




Sign up with Google



Sign up with GitHub



Sign up with Facebook




Stack Overflow for Teams
– Collaborate and share knowledge with a private group.



Create a free Team
What is Teams?


Asked
10 years, 3 months ago


Active
1 year, 2 months ago


python oop properties encapsulation


12.8k 36 36 gold badges 80 80 silver badges 106 106 bronze badges


36.1k 21 21 gold badges 94 94 silver badges 117 117 bronze badges



What do you mean by "declare"? Python has no declarations. So it's unclear what you mean when you use the word "declare". Please update your question to either replace the word "declare" or define what you mean by it.

–  S.Lott
Dec 29 '10 at 20:37



@SLott That's strange because e.g. chapter 9 of the Python tutorial mentions declarations (e.g. in the context of scoping). It seems to be used in the common sense (which could maybe be stated as "a statement, directive or expression that introduces a name").

–  Arne Vogel
Jul 29 '19 at 11:24



Related: stackoverflow.com/questions/1641219/… .

–  AMC
May 29 '20 at 4:08


23.3k 6 6 gold badges 61 61 silver badges 65 65 bronze badges



How do I argue/discuss with a Java dev that this does not make the programming language "worse" or that it doesnt just "miss a feature"?

–  raitisd
Dec 15 '16 at 15:18






I always point out that, unlike Ruby, Python, Scala, and C# (to name just a few), Java is actually worse, because it demonstrably fails to adhere to the Uniform Access Principle. As a result, the coder has to type (or the IDE has to generate) getters and setters defensively, most of which don't add any real value—and all of which mean there's more useless code to wade through when maintaining the class.

–  Brian Clapper
Feb 4 '17 at 20:27



@BillalBEGUERADJ : You can, like this: _ClassName__x . See this question.

–  Artemis
Jun 2 '18 at 13:44



@BrianClapper "fails to adhere to the Uniform Access Principle" - coming from the JVM world, this is what we're thought to avoid as it makes the code less "secure". I mean, let's imagine we have some mutable properties internal to the class and it's business logic that you want to hide from others... not sure I'd want that public. I'm interested in finding out why you think it is important to have this principle adhered to when building a language. Totally open-minded, give me some refs

–  milosmns
Jul 26 '19 at 12:51





1,925 1 1 gold badge 14 14 silver badges 38 38 bronze badges


1,621 3 3 gold badges 22 22 silver badges 34 34 bronze badges



However... you can access the attribute through a special way : f.__getattribute__('_Foo__attr') .

–  Philippe Fanaro
Jan 13 '20 at 19:30


146k 40 40 gold badges 205 205 silver badges 240 240 bronze badges



" In Python there is not private attributes ". So many times have I had to explain that encapsulation does not work similarly to other programming languages like Java...

–  Renato Damas
Jul 27 '20 at 14:19


11.3k 1 1 gold badge 30 30 silver badges 39 39 bronze badges



I know, but it's not my question. As you can see in my post, "private" and "public" are arrounded by quotes.

–  Sandro Munda
Dec 29 '10 at 16:47



Your question is meaningless then. It's like asking how to do garbage collection in C without using external libs. The facility just isn't built into the language.

–  Tyler Eaves
Dec 29 '10 at 16:52



@SeyZ if you want private and public and all that jazz, you should try Java, C# etc., Python isn't going to get it done for you

–  David Heffernan
Dec 29 '10 at 16:55



Nevertheless, the use of a leading underscore (or two, depending) is a well-established Python convention meaning, roughly, "Hey, don't access this directly. I might change it, remove it, or otherwise mess with it in future revisions of this class." Granted, that's not enforced privacy; it is , however, widely used in Python, and it is understood as being a form of conventional privacy.

–  Brian Clapper
Dec 29 '10 at 17:00





4,130 3 3 gold badges 22 22 silver badges 27 27 bronze badges


1,997 19 19 silver badges 21 21 bronze badges


836 9 9 silver badges 29 29 bronze badges



It should be noted that this doesn't actually make the variable private from the encapsulation perspective. All this does it perform a name mangling operation which CHANGES the way that one access the variable, but does not have the same effect as a true private variable from a OOP language such as Java. One need only access the variable at the name mangled name to get access to it.

–  Guardius
Sep 7 '17 at 12:33


3,243 4 4 gold badges 23 23 silver badges 26 26 bronze badges


24.6k 11 11 gold badges 73 73 silver badges 98 98 bronze badges

.NET Lead Developer (Russian speaking)
.net developer - for Europe’s Leading Product Company (m/f/d)
Full-Stack Engineer: Special Projects
1 - .NET, REACT and Azure Developer for a virtual team
GLOBAL APPCASTING AB No office location
Software Engineer (Python Experience)

Stack Overflow

Questions
Jobs
Developer Jobs Directory
Salary Calculator
Help
Mobile
Disable Responsiveness


Products

Teams
Talent
Advertising
Enterprise



Company

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



Stack Exchange Network

Technology
Life / Arts
Culture / Recreation
Science
Other




Stack Overflow
Server Fault
Super User
Web Applications
Ask Ubuntu
Webmasters
Game Development


TeX - LaTeX
Software Engineering
Unix & Linux
Ask Different (Apple)
WordPress Development
Geographic Information Systems
Electrical Engineering


Android Enthusiasts
Information Security
Database Administrators
Drupal Answers
SharePoint
User Experience
Mathematica


Salesforce
ExpressionEngine® Answers
Stack Overflow em Português
Blender
Network Engineering
Cryptography
Code Review


Magento
Software Recommendations
Signal Processing
Emacs
Raspberry Pi
Stack Overflow на русском
Code Golf


Stack Overflow en español
Ethereum
Data Science
Arduino
Bitcoin
Software Quality Assurance & Testing
Sound Design



Photography
Science Fiction & Fantasy
Graphic Design
Movies & TV
Music: Practice & Theory
Worldbuilding
Video Production


Seasoned Advice (cooking)
Home Improvement
Personal Finance & Money
Academia
Law
Physical Fitness
Gardening & Landscaping



English Language & Usage
Skeptics
Mi Yodeya (Judaism)
Travel
Christianity
English Language Learners
Japanese Language


Chinese Language
French Language
German Language
Biblical Hermeneutics
History
Spanish Language
Islam


Русский язык
Russian Language
Arqade (gaming)
Bicycles
Role-playing Games
Anime & Manga
Puzzling


Motor Vehicle Maintenance & Repair
Board & Card Games
Bricks
Homebrewing
Martial Arts
The Great Outdoors
Poker



MathOverflow
Mathematics
Cross Validated (stats)
Theoretical Computer Science
Physics
Chemistry
Biology



Meta Stack Exchange
Stack Apps
API
Data




Accept all cookies



Customize settings


Join Stack Overflow to learn, share knowledge, and build your career.
Connect and share knowledge within a single location that is structured and easy to search.
In Python, I have the following example class :
As you can see, I have a simple "private" attribute "_attr" and a property to access it. There is a lot of codes to declare a simple private attribute and I think that it's not respecting the "KISS" philosophy to declare all attributes like that.
So, why not declare all my attributes as public attributes if I don't need a particular getter/setter/deleter ?
My answer will be :
Because the principle of encapsulation (OOP) says otherwise!
Typically, Python code strives to adhere to the Uniform Access Principle . Specifically, the accepted approach is:
The main advantage to this approach is that the caller gets to do this:
even though the code might really be doing:
The first statement is infinitely more readable. Yet, with properties, you can add (at the beginning, or later on) the access control you get with the second approach.
Note, too, that instance variables starting with a single underscore are conventionally private. That is, the underscore signals to other developers that you consider the value to be private, and they shouldn't mess with it directly; however, nothing in the language prevents them from messing with it directly.
If you use a double leading underscore (e.g., __x ), Python does a little obfuscation of the name. The variable is still accessible from outside the class, via its obfuscated name, however. It's not truly private. It's just kind of ... more opaque. And there are valid arguments against using the double underscore; for one thing, it can make debugging more difficult.
The "dunder" (double underscore, __ ) prefix prevents access to attribute, except through accessors.
However, you can access this type of attribute through name mangling ( _classname__attribute ), which Python does in the background:
Quite simply, the OOP principles are wrong. Why this is is a long discussion which leads to flamewars and is probably off topic for this site. :-)
In Python there is not private attributes, you can't protect them, and this is never a real problem. So don't. Easy! :)
Then comes the question: Should you have a leading underscore or not. And in the example you have here you should definitely not. A leading underscore in Python is a convention to show that something is internal, and not a part of the API, and that you should use it on your own risk. This is obviously not the case here, but it's a common and useful convention.
Python doesn't have public OR private attributes. All attributes are accessible to all code.
Your method isn't in any way making _attr private, it's just a bit of obfuscation.
As others have said, private attributes in Python are merely a convention. The use of property syntax should be used for special processing when attributes are bound, modified or deleted. The beauty of Python is that you can start off by just using normal attribute binding, e.g., self.attr = 0 and if at some later date you decide you want to restrict the value of attr to say 0 <= attr <=100 , you can make attr a property and define a method to make sure this condition is true without ever having to change any user code.
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
To make an attribute private, you just have to do self.__attr
In Python, unless you need special behavior out of an attribute, there's no need to hide it behind accessor methods. If an attribute is for internal use only, prepend it with an underscore.
The nice thing about properties is that they given you a really cool interface to work with. Sometimes it's handy to derive a property based on some other (ie. BMI is defined by weight and height). The user of the interface doesn't have to know this of course.
I prefer this way over having explicit getters and setters like in Java ie. Way nicer. :)
Thanks for contributing an answer to Stack Overflow!

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa . rev 2021.4.6.38996


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


ООП Python 3: режимы доступа - public , private , protected.
Приватные методы без нижнего подчеркивания и интерфейсы в Python / Хабр
oop - " public " or " private " attribute in Python ? - Stack Overflow
Примеры работы приватных переменных в python ~ PythonRu
public , protected, private members in Python
ООП 9 Публичные, приватные, защищенные атрибуты и методы Python Public ...
Private , protected and public in Python
Access Modifiers in Python : Public , Private and Protected - GeeksforGeeks
Public , Private , and Protected — Access Modifiers in Python | Medium
Спасательный круг для собеседования на Python -разработчика
атрибут" public "или" private " в Python ? Каков наилучший способ?
Инкапсуляция, наследование, полиморфизм | Python 3 для начинающих...
Закрытые/приватные методы и переменные класса Python . | DOCS- Python .ru
Public , Private , and Protected — Access Modifiers in Python | by Sarath...
Частные методы в Python
Главная Уроки №33 Приватные переменные / для начинающих
Я создал этот блог в 2018 году, чтобы распространять полезные учебные материалы, документации и уроки на русском. На сайте опубликовано множество статей по основам python и библиотекам, уроков для начинающих и примеров написания программ.
Мои контакты:


Почта




Телеграм




Кью



© PythonRu 2018-2021 — Образовательный блог о Python
Приватные переменные — это те переменные, которые видны и доступны только в пределах класса, которому они принадлежат. В Java приватные переменные объявляются с помощью ключевого слова private , которое дает к ним доступ только переменным и методам внутри этого же класса. Такие методы не могут быть перезаписаны извне. В Python такого нет — вместо этого используются два символа нижнего подчеркивания ( __ ) для любых переменной или метода, которые должны считаться приватными.
На практике в Python нет приватных методов и переменных, как в Java. Здесь задействованы два символа нижнего подчеркивания в начале любой переменной или метода, которые нужно сделать приватными. Когда переменные объявляются приватными, подразумевается, что их нельзя будет изменять, как в случае с публичными. Последние доступны из любого класса, поэтому их значения могут меняться, что часто приводит к различным конфликтам. Рассмотрим на примере, как в Python используются приватные переменные.
Приватная переменная: 2020 Это приватный метод
В программе выше есть класс Mainclass , внутри которого имеются приватные переменные методы, объявленные с помощью двух подчеркиваний: __private_variable и __private_method . Получить к ним доступ можно только в пределах этого класса. Если же попробовать сделать это из другого класса, то вернется ошибка, сообщающая, что в классе нет такого атрибута. Это же можно продемонстрировать и на другом примере.
Private Variable: 2020 Traceback (most recent call last): File «C:\Python37\da.py», line 13, in foo.__private_method() AttributeError: ‘Mainclass’ object has no attribute ‘__private_method’
В этой программе можно обратить внимание на то, что метод приватный, но доступ к нему пытаются получить вне класса Mainclass , поэтому возвращается ошибка, которая сообщает, что у класса нет экземпляра этого атрибута. Таким образом по умолчанию все методы и переменные внутри класса являются публичными, но методы с двумя подчеркиваниями в названии становятся приватными, и получить к ним доступ можно только внутри того же класса.
Процесс превращения переменных или методов в локальные называется «искажением данных» или «искажением имен» (data/name mangling). Он используется для избежания неоднозначности при определении имен подклассов. Это же помогает перезаписывать методы подклассов без прерывания вызовов методов внутри класса.
Настоящая приватность в Python не поддерживается, а ту, что есть, называют «слабым индикатором внутреннего использования». Для нее есть один символ нижнего подчеркивания ( _ ), который используется для объявления приватных переменных, методов, функций и классов в модуле.
Создаем мотоцикл. Мотоцикл создан. Мотоцикл запущен.
В последнем примере нижнее подчеркивание используется для метода _start_engine чтобы сделать его приватным. Но такое подчеркивание применяется не часто, потому что оно лишь подразумевает, что к этому объекту нельзя будет получить доступ извне, а двойное подчеркивание означает то же, но соблюдается строже.
Одиночное подчеркивание используется не очень часто, потому что если метод с одним подчеркиванием изменяют любую переменную класса и при этом вызывается, то возможны конфликты в работе класса. Двойное подчеркивание же ( __ ) широко используется для объявления приватных переменных и избежания неоднозначности при определении имен подклассов. В Python не таких приватных переменных, как в C++ или Java.
В большей части языков программирования есть 3 модификатора доступа: публичный, приватный и защищенный. В Python они тоже есть, но работают и поддерживаются не совсем так.
Приватные переменные — это те переменные, к которым можно получить доступ внутри класса, где они были объявлены. В Python для этого есть одиночные и двойные подчеркивания, хотя вторые используются куда чаще. С их помощью можно получать доступ изнутри класса и выполнять «искажение имен».
У блога есть сообщество на Кью >> Python Q <<. Там я и другие участники отвечаем на вопросы по python, программированию и контенту сайта.






Report Page