Python类中super()函数和私有属性是如何实现继承和封装的原理是什么?

2026-04-20 05:201阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计357个文字,预计阅读时间需要2分钟。

Python类中super()函数和私有属性是如何实现继承和封装的原理是什么?

函数`super()`有参数写法:- `super([class[, object, ...]])`- 其中,`class`是当前类的父类,`object`是`class`的实例,用于调用父类中的方法。

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__类属性的顺序

私有属性与方法

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

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

Python类中super()函数和私有属性是如何实现继承和封装的原理是什么?

获取和修改私有属性:

在类中添加函数:

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

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

本文共计357个文字,预计阅读时间需要2分钟。

Python类中super()函数和私有属性是如何实现继承和封装的原理是什么?

函数`super()`有参数写法:- `super([class[, object, ...]])`- 其中,`class`是当前类的父类,`object`是`class`的实例,用于调用父类中的方法。

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__类属性的顺序

私有属性与方法

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

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

Python类中super()函数和私有属性是如何实现继承和封装的原理是什么?

获取和修改私有属性:

在类中添加函数:

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

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