具体区别看下面例子
1 class A: 2 def __init__(self,name=‘Andy‘): 3 self._name = name 4 5 class B: 6 def __init__(self,name = ‘Jack‘,age=19): 7 self.__name = name # 私有属性(变量),只有类对象自己能访问,子类也不能访问 8 self._age = age # 保护变量,类,及子类对象可以访问 9 10 class C(B): 11 def h(self): 12 print(‘hello‘) 13 14 a = A() 15 b = B() 16 c = C() 17 print(a._name) # 输出Adny 18 print(b._B__name) # 私有属性在类外的访问方式:对象._类__属性名 19 print(c._age) # 输出19 20 print(c._C__name) # AttributeError: ‘C‘ object has no attribute ‘_C__name‘子类不能访问
时间: 2024-11-05 16:32:37