Need Help with Encapsulation in Python!

Soham Mukherjee sohammm1087 at gmail.com
Fri Jun 17 14:21:09 UTC 2022


[Here](https://www.scaler.com/topics/python/encapsulation-in-python/), they mentioned a way of simulating encapsulation of class level like this:
```
def private(*values):
     def decorator(cls):
         class Proxy:
             def __init__(self, *args, **kwargs):
                 self.inst = cls(*args, **kwargs)
             def __call__(self, cls, *args, **kwargs):
                 return self.inst
             def __getattr__(self, attr):
                 if attr in values:
                     raise AttributeError("Private valueiables are 
not accessible!")
                 else: return getattr(self.inst, attr)
             def __setattr__(self, attr, val):
                 # Allow access inside the class
                 if attr == 'inst': self.__dict__[attr] = val
                 elif attr in values:
                     raise AttributeError("Private valueiables are 
not accessible!")
                 else: setattr(self.inst, attr, val)
             def __str__(self):
                 return self.inst.__str__()
         return Proxy
     return decorator
```
this can be used for class-level encapsulation (e.g.limiting the 
access of a variable or method in a class).

For module-level encapsulation, however, the only way that I can 
think of is that you create a file and write the init.py. However 
if those who writes the client program knows the structure of 
your file / package, this can still not stop them from importing 
stuff.



More information about the Digitalmars-d-learn mailing list