6.6 不想让子类继承的变量名该怎么写? ==================================== .. image:: http://image.iswbm.com/20200804124133.png 先来看下面这段代码 .. code:: python class Parent: def __init__(self): self.name = "MING" class Son(Parent): def __init__(self): self.name = "Xiao MING" bar = Son() print(bar.name) # 输出: Xiao MING Bar 作为 Foo 的子类,会继承父类的 name 属性。 如果有一些属性,是父类自己独有的,不想被子类继承,该怎么写呢? 可以在属性前面加两个下划线,两个类的定义如下 .. code:: python class Parent: def __init__(self): self.name = "MING" self.__wife = "Julia" class Son(Parent): def __init__(self): self.name = "Xiao MING" super().__init__() 从本章节的第一篇文章(\ `6.1 不要直接调用类的私有方法 `__\ )我们知道了私有的变量或函数,是不能直接调用的,需要用这样的形式才能访问 ``_类名__变量名``\ 。 从上面的代码中,可以看到 Son 类的实例并没有初始化 ``__wife`` 属性,虽然 Parent 类的实例有该属性,但由于这个属性是父类私有的,子类是无法访问的。因此当子类想要访问时,是会提示该变量不存在。 验证过程如下: .. image:: http://image.iswbm.com/20200823205210.png