封装
约定一:任何以单下划线开头的名字都应该是内部的,私有的
python并不会真的阻止你访问私有的属性,print(p1._star)依然是可以的
模块也遵循这种约定,如果模块名以单下划线开头,那么from module import时不能被导 入, 但是from module import _private_module依然是可以导入的
约定二:双下划线开头的名字
封装在类内部可以访问,在外部不能访问
#_*_coding:utf-8_*_ __author__ = 'Linhaifeng' class People: __star='earth111111111111' __star1='earth111111111111' __star2='earth111111111111' __star3='earth111111111111' def __init__(self,id,name,age,salary): print('----->',self.__star) self.id=id self.name=name self.age=age self.salary=salary def get_id(self): print('我是私有方法啊,我找到的id是[%s]' %self.id) #访问函数 def get_star(self): print(self.__star) p1=People('123123123123','alex','18',100000000) #-----> earth111111111111 # print(p1.__star) #报错:AttributeError: 'People' object has no attribute '__star' print(People.__dict__) #只要以__开头,python会自动重命名,例__star重命名为_People__star # {'__module__': '__main__', '_People__star': 'earth111111111111', '_People__star1': 'earth111111111111', '_People__star2': 'earth111111111111', '_People__star3': 'earth111111111111', '__init__': <function People.__init__ at 0x02FF6030>, 'get_id': <function People.get_id at 0x02FF6078>, 'get_star': <function People.get_star at 0x02FF60C0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None} print(p1._People__star) #earth111111111111 # # p1.get_star() p1.get_star() #earth111111111111
封装的本质:将事物相关的属性和方法封装在一个类里面,我们调用类创建实例的时候,不用关心类内部的代码细节,相当于一个黑箱子,我们只需要该实例(黑箱)能给出我们想要的结果就好了。