【Python基础编程220 ● 面向对象 ● 子类不能继承父类中私有的属性和方法】


---------Python基础编程---------

Author : AI菌


【内容讲解】

子类不能继承父类中私有的属性和方法

【代码演示】

"""
  1.子类不能继承父类中私有的属性和方法
"""


class Father:
    def __init__(self, money, house):
        self.money = money
        self.house = house
        # 私有属性
        self.__girl_friend = "rabbit"

    def run_company(self):
        print("父亲经营的公司")

    # 私有方法
    def __love(self):
        print(f"父亲年轻时与{self.__girl_friend}谈恋爱")


class Son(Father):
    pass


# 创建儿子对象
s = Son("2000000000", "海景别墅")

# 调用继承的非私有属性
print(s.money)
print(s.house)

# 调用继承的非私有方法
s.run_company()

# 调用父类的私有属性
# 报错: 'Son' object has no attribute '__girl_friend'
# print(s.__girl_friend)

# 调用父类的私有方法
# 报错: AttributeError: 'Son' object has no attribute '__love'
# s.__love

【往期精彩】

▷【Python基础编程196 ● 读取文件的4种方式】
▷【Python基础编程197 ● 读取文件的4种方式】
▷【Python基础编程198 ● 读取文件的4种方式】
▷【Python基础编程199 ● Python怎么读/写很大的文件】
▷【Python基础编程200 ● 读取文件的4种方式】
▷【Python基础编程201 ● 读取文件的4种方式】
▷【Python基础编程202 ● 读取文件的4种方式】
▷【Python基础编程203 ● 读取文件的4种方式】

 

【加群交流】



原文地址:https://www.cnblogs.com/hezhiyao/p/13424535.html