您的位置:首页技术文章
文章详情页

Python类super()及私有属性原理解析

浏览:14日期:2022-07-21 11:48:56

super()有参数写法:

# 1.定义父类class A(object): def __init__(self): self.num = 1 def info_print(self): print(self.num)class C(A): def __init__(self): self.num = 2 def info_print(self): print(self.num) super(C, self).__init__() super(C, self).info_print()# 2. 定义子类,继承父类class B(C): def __init__(self): self.num = 3 def info_print(self): self.__init__() print(self.num) def print_A(self): A.__init__(self) A.info_print(self) def print_C(self): C.__init__(self) C.info_print(self) def print_AC(self): super(B, self).__init__() super(B, self).info_print()b = B()b.print_AC()

super()用于调用父类的方法

无参写法:

super().__init__()super().info_print()

使用super()方法可以自动查找父类,查找顺序遵循__mro__类属性的顺序

私有属性与方法

设置私有极限的方法:在属性名和方法名前面加上两个下划线__

设置之后设置的实例属性或实例方法不继承给子类

获取和修改私有属性:

在类中添加函数:

def get_money(self): return self.__moneydef set_money(self, money): self.__money = money

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: Python 编程
相关文章: