class Father(object):
def __init__(self, name, age):
self.__privateFatherAge = age;
self.publicFatherName = name;
#定义共有属性和私有属性!
__privateFatherAge = 44;
publicFatherName = 'feige';
#私有方法访问共有属性
def __privateMethod(self):
print('the name of father is:'+self.publicFatherName);
#共有方法访问私有属性!
def publicMethod(self):
print('the age of father is :'+str(self.__privateFatherAge));
f = Father('fei', 24);
print(f.publicFatherName);
#print(f.__privateAge);出错
print(f._Father__privateFatherAge);
f.publicMethod();
#f.__privateMethod();出错
f._Father__privateMethod();
#f2 = Father();出错
fei
24
the age of father is :24
the name of father is:fei
Phyton在编译的时候动了手脚,所以访问私有属性或者私有方法会报错,你要你按照特殊的形式,就可以访问私用属性或者私有方法了。
Python目前的私有机制是虚伪私有,Python的类是没有权限控制的,所有的变量都是可以被外部访问的。
原文:https://www.cnblogs.com/feiqiangsheng/p/10921287.html