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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

鸡龟骨滚羹   2021-04-22 我要评论

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.__money
def set_money(self, money):
  self.__money = money

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们