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()#我不告訴你我多少歲