2012年5月1日 星期二

python encapsulation

python 其實並不支援真正的encapsulation (封裝)
但是利用 name mangling 的方式限制些許的access權限





class A (object):
    def __init__(self,hasperm1,hasperm2,private1,private2):
        self.hasperm1 = hasperm1
        self.hasperm2  = hasperm2
        self.private1 = private1 
        self.private2 = private2
    def __dir__(self):
        return ["hasperm1","hasperm2"]


a = A("v1","v2","v3","v4")
print dir(a)
>>
['hasperm1', 'hasperm2']


Encapsulation: Python does not really support encapsulation because it does not support data hiding through private and protected members. However some pseudo-encapsulation can be done. If an identifier begins with a double underline, i.e. __a, then it can be referred to within the class itself as self.__a, but outside of the class, it is named instance._classname__a. Therefore, while it can prevent accidents, this pseudo-encapsulation cannot really protect data from hostile code.

沒有留言:

張貼留言