# -*- coding: utf-8 -*-
"""
封装(Encapsulation)是对对象(object)的一种抽象,即将某些部分隐藏起来,在程序外部看不到,无法调用
封装离不开私有化,私有化是指将某个对象限定在某个自己认定的范围内
私有化的方法:将准备私有化的属性对象前面加双下划线
"""
class Encap:
def __init__(self,name,age):
self.name=name #公有化属性name
self.__age=age #私有化属性age
def __f1(self): #私有化方法
print(self.name," by private method f1")
print(self.__age," by private method f1")
def f2(self): #公有化方法
print(self.name," by public method f2")
print(self.__age," by public method f2")
def f3(self):
print(self.__age,"by f3")
self.__f1()
if __name__=="__main__":
e=Encap("as",12)
print(e.name)
#print(e.__age) 报错AttributeError: 'Encap' object has no attribute '__age',__age是私有成员,外部对象无法访问
#e.__f1() 报错AttributeError: 'Encap' object has no attribute '__f1'
e.f2()
e.f3() #可以通过f3()内部调用__f1()
实验运行结果:
as
as by public method f2
12 by public method f2
12 by f3
as by private method f1
12 by private method f1