I am not very experienced in OOP in python, I was just wondering if I should make an attribute .__private if I need to use it outside the class (Use it by creating a getter method returning the attribute I need) or should I just keep those attributes .public
Asked
Active
Viewed 42 times
0
-
1you could make it private and create getters and setters, or you could use `@property`. A good read about this topic https://www.programiz.com/python-programming/property – Omar Einea Jan 16 '18 at 18:03
-
It's hard to answer it without the specific example, both ways are possible. In general I would suggest not exposing the attributes at all, keep them private and have no getter. – Borys Serebrov Jan 16 '18 at 18:05
-
Python doesn't *really* support private attributes. The conventional use is prefixing the attributes with `_`s as you have done like `__private`, it'll be hidden from most auto-complete features. But if you want to access `__private` from outside the class, nothing can stop you. Read more on this relevant thread: https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes – r.ook Jan 16 '18 at 18:09
-
Based on [this](https://meta.stackexchange.com/questions/68384/whats-the-difference-between-stack-overflow-and-software-engineering-se-previo) I think you should consider to ask this question on [Software Engineering SE](http://softwareengineering.stackexchange.com) – Peter Jan 16 '18 at 18:10
-
I have python 3.4 and I think it is supporting the private attributes. E.g. class Human, with an attribute __name. If I do Human = Human() and then print(Human._name) It says Human has no attribute __name – Jan 16 '18 at 18:11
-
you can get the mangled name out of the `__dict__` and access it. its not private as in private its just mangled. just read what @Idlehands posted. – Patrick Artner Jan 16 '18 at 18:18
-
@Peter when referring other sites, it is often helpful to point that [cross-posting is frowned upon](https://meta.stackexchange.com/tags/cross-posting/info) – gnat Jan 16 '18 at 21:32