这有什么问题吗?从客观和功能的角度来看?
import sys
class EncapsulationClass(object):
def __init__(self):
self.privates = ["__dict__", "privates", "protected", "a"]
self.protected = ["b"]
print self.privates
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" % name)
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
这样做实际上有什么问题呢?
Python中有没有更好的方法来实现封装?
Python 有封装——你在你的类中使用它。
它没有访问控制,例如私有和受保护的属性。然而,在 Python 中,有一种属性命名约定,通过在属性前添加一个或两个下划线来表示私有属性,例如:
self._a
self.__a
单个下划线向类的用户指示属性应被视为类的私有属性,并且不应直接访问。
双下划线表示相同,但是,Python 会在某种程度上修改属性名称以尝试隐藏它。
class C(object):
def __init__(self):
self.a = 123 # OK to access directly
self._a = 123 # should be considered private
self.__a = 123 # considered private, name mangled
>>> c = C()
>>> c.a
123
>>> c._a
123
>>> c.__a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute '__a'
>>> c._C__a
123
您可以在最后一个示例中看到名称已更改为__a
to _C__a
,尽管它仍然可以在类中访问self.__a
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)