Skip to Content
Menu
This question has been flagged
1 Reply
1323 Views

I am stuck here, can anybody tell what 's wrong with my code ?  


[code]
self.a = 1

self.b = 2

self.c = 3

pass



def __getattribute__(self, name):

if sys._getframe(1).f_code.co_argcount == 0:

if name in self.privates:

raise Exception(" Access to private attribute \"%s\" is not allowed" % name)

else:

return object.__getattribute__(self, name)

else:

return object.__getattribute__(self, name)



def __setattr__(self, name, value):

if sys._getframe(1).f_code.co_argcount == 0:

if name in self.privates:

raise Exception("Setting private attribute \"%s\" is not allowed"

elif name in self.protected:

raise Exception("Setting protected attribute \"%s\" is not allowed" % name)

else:

return object.__setattr__ (self, name, value)

else:

return object.__setattr__(self, name , value)





example = EncapsulationClass()



example.a = 10 # Exception: Setting private attribute "a" is not allowed

example.b = 10 # Exception: Setting protected attribute "b" is not allowed

example.c = 10 # example.c == 10



example.__dict__["privates"] # Exception: Setting protected attribute "b" is not allowed
[/code]


Is there any better way to achieve encapsulation in Python?


Avatar
Discard
Best Answer

You can use "_" and "__" before attribute-names and method-names as visibility qualifiers in Python. 

E.g.:

class Example:
    
    def __init__(self):
        self._protected = "This is protected"
        self.__private = "This is private"

NOTE: While you can use this, there is no hard enforcing of those. They still can be accessed with some tricks. But at least they are not easily accessible via the dot-notation from outside. And this is considered as not "pythonic" by some. But I use it without having problems and being aware that problems could arise with so called "name-mangling", this is one of the reasons to test my code extensively.

Avatar
Discard
Related Posts Replies Views Activity
4
Apr 24
170732
0
Dec 23
609
5
Nov 24
217144
1
Dec 22
1693
2
Nov 22
1680