1 class Animal: 2 cls_attr = 'cls_attr' 3 _cls_attr = '_cls_attr' 4 __cls_attr = '__cls_attr' 5 6 def __init__(self): 7 self.ins_attr = 'ins_attr' 8 self._ins_attr = '_ins_attr' 9 self.__ins_attr = '__ins_attr' 10 print('Animal __init__') 11 12 def func(self): 13 print('func') 14 15 def _func(self): 16 print('_func') 17 18 def __func(self): 19 print('__func') 20 21 def __del__(self): 22 print('Animal __del__') 23 24 25 class Dog(Animal): 26 27 def __init__(self): 28 '''子类重写__init__函数时,需手动调用父类的__init__函数''' 29 print('Dog __init__') 30 super(Dog, self).__init__() 31 32 def __del__(self): 33 print('Dog __del__') 34 super(Dog, self).__del__() 35 36 37 a = Animal() 38 print(a.cls_attr) 39 print(a._cls_attr) 40 # print(a.__cls_attr) 41 print(a._Animal__cls_attr) 42 print(a.ins_attr) 43 print(a._ins_attr) 44 # print(a.__ins_attr) 45 print(a._Animal__ins_attr) 46 a.func() 47 a._func() 48 # a.__func() 49 a._Animal__func() 50 del a 51 52 print('-' * 50) 53 54 d = Dog() 55 print(d.cls_attr) 56 print(d._cls_attr) 57 # print(d.__cls_attr) 58 print(d._Animal__cls_attr) 59 print(d.ins_attr) 60 print(d._ins_attr) 61 # print(d.__ins_attr) 62 print(d._Animal__ins_attr) 63 d.func() 64 d._func() 65 # a.__func() 66 d._Animal__func() 67 del d
1 Animal __init__ 2 cls_attr 3 _cls_attr 4 __cls_attr 5 ins_attr 6 _ins_attr 7 __ins_attr 8 func 9 _func 10 __func 11 Animal __del__ 12 -------------------------------------------------- 13 Dog __init__ 14 Animal __init__ 15 cls_attr 16 _cls_attr 17 __cls_attr 18 ins_attr 19 _ins_attr 20 __ins_attr 21 func 22 _func 23 __func 24 Dog __del__ 25 Animal __del__