这是怎么回事?从客观和功能的角度?
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没有封装作为一种“哲学”决策,就像我们经常使用duck类型一样。就我个人而言,我不认为在Python代码中使用私有或受保护的参数有什么意义。
说到您的代码,它似乎可以与以下getter和setter一起工作:
如果对“getattribute”(self,name)的最后一行进行以下修改:
然而,正如mhawke所提到的,如果在私有变量前面加上前缀,则可以使用某种变量保护的概念。另外,丹尼尔的评论指出了你的列表论点的局限性。通过在私有列表中添加“private”和“protected”,可以保持受保护的“get/set”行为。
因此,Python 3提供了3个级别的数据访问:
1.public(public,没有特殊语法,publicVariable)
2.受保护(受保护,名称开头有一个下划线,即protectedVariable)
3.private(private,名称开头的两个下划线,privateVariable)。
最后一个是封装,这意味着限制对对象组件(变量,方法)的访问,你可以在类内定义方法,这样用户就可以看到变量,甚至可以更改它,如果他想给用户这样的特权,就依赖于程序员,所以简单地说,它实际上给了程序员调用什么是公共的什么是内部的
private和public是基本的和典型的用法,下面是一个例子
`
`
Python具有封装——您正在类中使用它。
它没有的是访问控制,比如私有和受保护的属性。但是,在Python中,有一个属性命名约定,通过在属性前面加上一个或两个下划线来表示私有属性,例如:
单个下划线向类的用户指示,属性应被视为该类的私有属性,而不应直接访问。
双下划线表示相同,但是,Python将对属性名进行某种程度的篡改,以试图隐藏它。
在上一个示例中,您可以看到名称已从
__a
更改为_C__a
,尽管它在类中仍然可以作为self.__a
访问。相关问题 更多 >
编程相关推荐