python对象的私有封装


python的实例非常灵活,在某些情况下,如果想实现隐藏和封装性时就需要一些小操作来提高python的准确性.
_attr真不靠谱
_属性只是提供模块级别的隐藏,定义_属性,在实例中,仍然可以随意操作。
 
三个办法变得靠谱
# 1.藏. 私有属性 __name , 达到隐藏的效果,但并不能保证属性被意外染指
# 2.护 property函数 ,达到封装性,只有显示操作才能达到效果
# 3.限 __slot__ : 给python实例这个野孩子加紧箍咒, 禁止随意添加属性

01 # -*-coding:utf-8 -*-
02  
03 """
04  @author: 回忆书签
05  @version: 0.1
06  @date:  2010-06-16
07  @description:   python类中属性的私有封装
08 """
09  
10  
11 class A(object):
12  
13     def __init__(self,name):
14         self.__name=name  # 第一招 :私有属性
15         self.abc=123
16  
17     @property
18     def name(self):
19     # 第二招, 公有方法name得到__name,在外界看name是一个属性,而实际上name是一个函数的返回值.
20         # 而函数的输出是不能直接改变的,除非直接修改__name,而第一个办法已经把__name藏起来了。.
21         return self.__name
22  
23     @name.setter
24     def setName(self,value):
25     #共用方法setName,这里没有命名为name,是故意让使用者意识到自己在做什么。
26     #想要改变__name只有通过这个入口
27         if not isinstance(value,str):
28             raise TypeError('must be a string')
29         self.__name=value
30  
31     @name.deleter
32     def delName(self):
33         del self.__name
34  
35     __slots__ = ('__name','abc') 
36         #第三招限制实例属性,将墙内的属性都规定好,以后再想挤进来属性就只能到这里来定义
 
#实例化看看

1 if __name__ == "__main__":
2     a=A('abc')
3     print a.name
4     a.setName='xyz'
5     print a.name
6         a.abc=4567
 #如果还想增加几个打酱油的进来,想也别想

1 a.dajiangyou=456

1 Traceback (most recent call last):
2 a.dajiangyou=456  AttributeError: 'A' object has no attribute 'dajiangyou'
#这个__name是动态加的李鬼,有了slot,李鬼立刻现形了。

1 a.__name='yyy'

1 Traceback (most recent call last):
2 File "encloseattr.py", line 48, in <module> # a.__name='yyy'
3 AttributeError: 'A' object has no attribute '__name'
#   墙内众生真面目: 谁是公有的谁是私有的一看便知道

01 print dir(a)
02     #  墙内众生真面目: 谁是公有的谁是私有的一看便知道
03     # ['_A__name',
04     # '__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__',
05     # '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__',
06     # '__subclasshook__',
07     # 'abc',  #公有属性,没有任何修饰www.2cto.com
08     # 'delName',
09     # 'name',  #公有的getter
10     # 'setName' #公有的setter

相关内容

    暂无相关文章

评论关闭