脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 类的继承实例详解

Python 类的继承实例详解

2020-09-25 10:26Python教程网 Python

这篇文章主要介绍了Python 类的继承实例详解的相关资料,需要的朋友可以参考下

Python 继承详解

Python既然是面向对象的,当然支持类的继承,Python实现类的继承比JavaScript简单。

Parent类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Parent:
 
  parentAttr = 100
 
  def __init__(self):
    print("parent Init")
 
  def parentMethod(self):
    print("parentMethod")
   
  def setAttr(self,attr):
    self.parentAttr = attr
 
  def getAttr(self):
    print("ParentAttr:",Parent.parentAttr)

Child类

?
1
2
3
4
5
6
7
class Child(Parent):
 
  def __init__(self):
    print("child init")
 
  def childMethod(self):
    print("childMethod")

调用

?
1
2
3
4
5
p1 = Parent();
p1.parentMethod();
 
c1 = Child();
c1.childMethod();

输出:

?
1
2
3
4
5
parent Init
parentMethod
child init
childMethod
Press any key to continue . . .

Python支持多继承

?
1
2
3
4
5
6
7
8
class A:    # 定义类 A
.....
 
class B:     # 定义类 B
.....
 
class C(A, B):  # 继承类 A 和 B
.....

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

延伸 · 阅读

精彩推荐