python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python super()

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

作者:鸡龟骨滚羹

这篇文章主要介绍了Python类super()及私有属性原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

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

您可能感兴趣的文章:
阅读全文