1.隐藏的使用场景
在Python类中,有些属性和方法只希望在对象的内部被使用,而不希望在外部被访问到,
2.定义方式, 在属性名或方法名前增加两个下划线,定义的就是私有属性或方法
#其实这仅仅这是一种变形操作且仅仅只在类定义阶段发生变形 #类中所有双下划线开头的名称如__x都会在类定义时自动变形成:_类名__x的形式: class A: __N=0 #类的数据属性就应该是共享的,但是语法上是可以把类的数据属性设置成私有的如__N,会变形为_A__N def __init__(self): self.__X=10 #变形为self._A__X def __foo(self): #变形为_A__foo print('from A') def bar(self): self.__foo() #只有在类内部才可以通过__foo的形式访问到. #A._A__N是可以访问到的, #这种,在外部是无法通过__x这个名字访问到。
但其实这不是真的隐藏,
可以通过对象._类名__属性 获取到这个私有熟悉(不建议这样做)
# 封装数据属性的真实意图 class People: def __init__(self,name,age): self.__name=name self.__age=age def get_info(self): print('<name:%s,age:%s>'%(self.__name,self.__age)) def set_info(self,new_name,new_age): if type(new_name) is not str: print('名字必须是str类型') return elif type(new_age)is not int: print('年龄必须是int类型') return self.__name=new_name self.__age=new_age obj1=People('maple',18) obj1.get_info() obj1.set_info('angel',20)
真实意图往往是在内部提供方法,获取或修改属性(方法).