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?
To pytanie dostało ostrzeżenie
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.
Podoba Ci się ta dyskusja? Dołącz do niej!
Stwórz konto dzisiaj, aby cieszyć się ekskluzywnymi funkcjami i wchodzić w interakcje z naszą wspaniałą społecznością!
Zarejestruj się| Powiązane posty | Odpowiedzi | Widoki | Czynność | |
|---|---|---|---|---|
|
|
0
mar 26
|
10 | ||
|
|
0
mar 25
|
3543 | ||
|
|
4
kwi 24
|
177586 | ||
|
|
0
gru 23
|
3860 | ||
|
|
5
lip 25
|
235383 |