On Friday, 17 June 2022 at 14:14:57 UTC, Ola Fosheim Grøstad wrote:
On Friday, 17 June 2022 at 13:58:15 UTC, Soham Mukherjee wrote:
Is there any better way to achieve encapsulation in Python? Please rectify my code if possible.

One convention is to use "self._fieldname" for protected and "self.__fieldname" for private class attributes.

Example:

```python
class A:
     def __init__(self):
         self._x = 3
         self.__x = 4

a = A()
print(a.__dict__)
```
will produce the output: ```{'_x': 3, '_A__x': 4}``` .

As you can see the "self.__x" field has the name "_A__x" which makes it "hidden", but not inaccessible.

But you can use external tools to check for misuse.

Reply via email to