python 类属性和实例属性、方法 访问权限问题

class Animal:
     cls_attr = 'cls_attr'
     _cls_attr = '_cls_attr'
     __cls_attr = '__cls_attr'
 
     def __init__(self):
         self.ins_attr = 'ins_attr'
         self._ins_attr = '_ins_attr'
         self.__ins_attr = '__ins_attr'
         print('Animal __init__')
 
     def func(self):
         print('func')
 
     def _func(self):
         print('_func')
 
     def __func(self):
         print('__func')
 
     def __del__(self):
         print('Animal __del__')
 
 
 class Dog(Animal):
 
     def __init__(self):
         '''子类重写__init__函数时,需手动调用父类的__init__函数'''
         print('Dog __init__')
         super(Dog, self).__init__()
 
     def __del__(self):
         print('Dog __del__')
         super(Dog, self).__del__()
 
 
 a = Animal()
 print(a.cls_attr)
 print(a._cls_attr)
 # print(a.__cls_attr)
 print(a._Animal__cls_attr)
 print(a.ins_attr)
 print(a._ins_attr)
 # print(a.__ins_attr)
 print(a._Animal__ins_attr)
 a.func()
 a._func()
 # a.__func()
 a._Animal__func()
 del a
 
 print('-' * )
 
 d = Dog()
 print(d.cls_attr)
 print(d._cls_attr)
 # print(d.__cls_attr)
 print(d._Animal__cls_attr)
 print(d.ins_attr)
 print(d._ins_attr)
 # print(d.__ins_attr)
 print(d._Animal__ins_attr)
 d.func()
 d._func()
 # a.__func()
 d._Animal__func()
 del d
Animal __init__
 cls_attr
 _cls_attr
 __cls_attr
 ins_attr
 _ins_attr
 __ins_attr
 func
 _func
 __func
 Animal __del__
 --------------------------------------------------
 Dog __init__
 Animal __init__
 cls_attr
 _cls_attr
 __cls_attr
 ins_attr
 _ins_attr
 __ins_attr
 func
 _func
 __func
 Dog __del__
 Animal __del__

相关推荐