5 ms·
Object Oriented Programming in Python: Encapsulation and Inheritance
- Walkman 9y agoThere is no such thing as "private" or "public" instance variable in Python. This guy should not teach...
- Sjenk 9y agoWell it is not intergrated in the language like i.e Java or C#. But Python does have the naming convention to mark vars that should not be touched with __ [0] [0] https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references https://docs.python.org/2/tutorial/classes.html#private-vari...
- orf 9y agoThat's just a single underscore for the convention. Double underscore actually mangles the attribute name (it prefixes it with the class name), so that's "really really don't touch this". It's hardly ever used though.
- masklinn 9y ago> that's "really really don't touch this". That's not. The use case for name mangling was "avoid the risk of conflict when designing classes for inheritance": if you're building classes for inheritance, subclasses using the same name for an internal/private attribute are not going to unwittingly collide with the base classe's.
- orf 9y agoSure that was the idea, but I don't think I have ever seen any code use it like this. A single underscore is something that's not part of the classes public API, any child classes may need to change attributes, and by using a double underscore you are saying "I know better than you, you won't ever need to change this", which is never true. Python isn't like Java where you often have complex and often convoluted class heirachies, where truly private attributes might be more useful.
- travisjungroth 9y agoYou and the article author both didn't seem to read that link. A single leading underscore is a convention to mark a variable as private. A double leading underscore "name mangles" the variable (adds the class to the name of the variable) and has a specific use case for inheritance. They're class level private, which is probably not what you want. class Number: def __init__(self, n): self._number = n self.__number = n class NumberChild(Number): def one_higher(self): return self._number + 1 def two_higher(self): return self.__number + 2 number_child = NumberChild(10) number_child.one_higher() # This works number_child.two_higher() # This raises an Attribute Error
- geezerjay 9y agoExactly. This is even stated quite clearly in PEP 8. https://www.python.org/dev/peps/pep-0008/ https://www.python.org/dev/peps/pep-0008/
- eire1130 9y agoSure, but I think this is what the author is getting at: >>> class A: ... def __a(self,b): ... return b ... >>> A() <__main__.A object at 0x0000024EE5B0EBE0> >>> A().__a('b') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'A' object has no attribute '__a' >>> a=A() >>> dir(a) ['_A__a', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] >>> a._A__a("b") 'b' In practice, I have never seen this used and just confuses things - and for dev's coming from Java / C++ or some other language it tends to just confuse things.
- metaobject 9y agoI agree. He is 100% wrong when he says: "This is the main difference between public and private variables. We can’t direct access or set a new value out of our class." He should just start off by saying that there are no private methods or variables, but instead a naming convention should be used to discourage users of the class from accessing them directly.
- thesmallestcat 9y agoYou're right, I skimmed related posts from "T.k." and they're full of the same muddled thinking. A "List"'s fundamental operation is random access? A "List" is either a "Collection" or an "Array"? Wut? It seems like most "code camp" teachers know just enough to give a passable performance. There's no depth of knowledge but given the brevity of these courses, maybe it's a moot point. Still, this guy should focus less on his Brand and more on getting up to snuff.
- sotojuan 9y ago"Brand" seems to be the name of the game lately. We encourage these "beginner experts" to post tutorials and articles because "everyone should blog!"/"our publication wants more views" yet we do no hold them accountable to their poor research and writing. We may laugh and ignore this guy, but these kind of posts can seriously hurt and confuse beginners. What sucks is that this guy seems genuinely nice and wants to help... but IDK. I personally would never post anything unless I am 100% sure it's correct (when applicable).
- jraedisch 9y agoThis way there won't be any potentially helpful comments though. Why not add a disclaimer stating you are still learning or something similar? Just don't claim to be an expert.
- smegel 9y agoHe should not program either. Python has an idiomatic way to control attribute access - descriptors. Mashing Java getter/setter methods into Python is so, so unpythonic.
- fermigier 9y agoMuch of the code in the post could be simplified by using the awesome `attrs` package [1]. Or if / when PEP 557 gets adopted. [1]: https://github.com/python-attrs/attrs https://github.com/python-attrs/attrs [2]: https://www.python.org/dev/peps/pep-0557/ https://www.python.org/dev/peps/pep-0557/
- smegel 9y agoThat looks good. Python has long needed something like this.