Python进阶学习


Python中的访问限制

 1 '''
 2 私有属性是以双下划线'__'开头的属性,在类的外部访问私有属性将会抛出异常,提示没有这个属性。
 3 '''
 4 
 5 class Animal:
 6     __location='china'
 7     def __init__(self,name,age):
 8         self.name=name
 9         self.__age=age
10 
11 #__location是类的私有属性,在class外部无法直接访问
12 print(Animal.__location)
13 dog=Animal('dog',3)
14 print(dog.name)
15 #__age是对象的私有属性,在class外部无法直接访问
16 print(dog.__age)