0

Python encapsulation vs Java encapsulation

When I lerned Java, encapsulation was a fundamental part of coding, even it have their own reserved words for that. But now that I’m lesrning python i can see that it is not the same. Does encapsulation is important in python? Is it really needed like in Java?

29th Jun 2021, 5:21 PM
Joaquin Alberto Vidal Palacios
Joaquin Alberto Vidal Palacios - avatar
4 Answers
+ 1
the principle is that an object, as such, has a state and accepts messages via an interface. not having a correct encapsulation means being able to bring the object into an unexpected state with possible malfunction or crash of the program. but the attention in the oop goes beyond hiding the data, so much so that we also try to hide the classes, for many good reasons, basing the use of objects on interfaces and abstract classes regardless of the real class used to instantiate the object. Bad encapsulation in the real world. Imagine a TV without a case. you have free access to its internal electrical state. instead of modifying it with the buttons (interface), let your finger on a copper track. you are electrocuted, the television changes its state to electrocuted and shuts down and the program ends unexpectedly. đŸ€Ł of python I only followed the core course and it was enough for me to decide that I don't like it
29th Jun 2021, 6:11 PM
Ciro Pellegrino
Ciro Pellegrino - avatar
+ 1
python doesn't provide real encapsulation by design choice: all properties/attributes of an object are always accessible from anywhere (if you got a reference to this object), as there's no real way to make them private or protected private like properties rely on developers attention: use of underscore at start of a property name means "this is a private property: don't use it or at your own risk"... similary another level of privacy is introduced by using double underscore at start of a property name wich means "this is a private (protected) property wich should be accessed with full qualified name from outside if you really want to" class Obj: def __init__(self): self._spam = 42 self.__egg = "forty-two" @property def spam(self): return self._spam @property def egg(self): return self.__egg o = Obj print(o.spam, o.egg) print(o._spam, o._Obj__egg) print(o.__egg) last one throw error learn more: https://dbader.org/blog/meaning-of-underscores-in-python
29th Jun 2021, 8:02 PM
visph
visph - avatar
0
I think java is better in encapsulation
29th Jun 2021, 5:50 PM
Sheikh Mohammed Owais
Sheikh Mohammed Owais - avatar
0
java therefore doesn't even have global variables, python does. java more promotes the use of objects.
29th Jun 2021, 6:07 PM
zemiak