python3中的私有属性和方法是以__两个下划线开头的:
class People():#定义一个类
def __init__(self, name, age):
self.name = name#公有属性
self.__age = age#私有属性
def __money(self):#私有方法
print('我不告诉你我多少岁')
p = People('小华', 'xx')
print(p.name)#小华
# print(p.__age)#AttributeError: 'People' object has no attribute '__age'
# p.__money()#AttributeError: 'People' object has no attribute '__money'
第一种访问:访问私有属性和方法的方式(在类内,普通方法可以访问私有属性和方法,然后再调用普通方法来访问私有的):
class People():#定义一个类
def __init__(self, name, age):
self.name = name#公有属性
self.__age = age#私有属性
def __money(self):#私有方法
print('我不告诉你我多少岁')
#定义一个普通方法来访问私有方法
def get_money(self):
self.__money()
##定义一个普通方法来访问私有属性
def get_age(self):
print(self.__age)
p = People('小华', 'xx')
print(p.name)#小华
# print(p.__age)#AttributeError: 'People' object has no attribute '__age'
# p.__money()#AttributeError: 'People' object has no attribute '__money'
p.get_age()#xx
p.get_money()#我不告诉你我多少岁
第二种访问:访问私有属性和方法的方式(通过_类名__私有(属性或方法))
class People():#定义一个类
def __init__(self, name, age):
self.name = name#公有属性
self.__age = age#私有属性
def __money(self):#私有方法
print('我不告诉你我多少岁')
#定义一个普通方法来访问私有方法
def get_money(self):
self.__money()
##定义一个普通方法来访问私有属性
def get_age(self):
print(self.__age)
p = People('小华', 'xx')
print(p.name)#小华
# print(p.__age)#AttributeError: 'People' object has no attribute '__age'
# p.__money()#AttributeError: 'People' object has no attribute '__money'
p.get_age()#xx
p.get_money()#我不告诉你我多少岁
#使用实例对象._类名__属性/方法名的方式来访问私有属性或私有方法。
print(p._People__age)#xx
p._People__money()#我不告诉你我多少岁