Python 类的继承实例详解

yipeiwu_com5年前Python基础

Python 类的继承详解

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

Parent类:

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类

class Child(Parent): 
 
  def __init__(self): 
    print("child init") 
 
  def childMethod(self): 
    print("childMethod") 

调用

p1 = Parent(); 
p1.parentMethod(); 
 
c1 = Child(); 
c1.childMethod(); 

输出:

parent Init 
parentMethod 
child init 
childMethod 
Press any key to continue . . . 

Python支持多继承

class A:    # 定义类 A 
..... 
 
class B:     # 定义类 B 
..... 
 
class C(A, B):  # 继承类 A 和 B 
..... 

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

相关文章

Python3 利用requests 库进行post携带账号密码请求数据的方法

如下所示: import urllib,json,requests url = 'http://127.0.0.1:8000/account/login' headers = {}...

python魔法方法-属性访问控制详解

python魔法方法-属性访问控制详解

属性访问控制 所谓的属性访问控制就是控制点号访问属性的行为,而且不仅是类的外部,连类的内部也受控制,代码见真章,边看代码边解释: •__getattr__(self, ite...

Python中Numpy mat的使用详解

前面介绍过用dnarray来模拟,但mat更符合矩阵,这里的mat与Matlab中的很相似。(mat与matrix等同) 基本操作 >>> m= np.mat([1...

Python 实现王者荣耀中的敏感词过滤示例

王者荣耀的火爆就不用说了,但是一局中总会有那么几个挂机的,总能看到有些人在骂人,我们发现,当你输入一些常见的辱骂性词汇时,系统会自动将该词变成“*”,作为python初学者,就想用pyt...

TensorFlow基于MNIST数据集实现车牌识别(初步演示版)

TensorFlow基于MNIST数据集实现车牌识别(初步演示版)

在前几天写的一篇博文《如何从TensorFlow的mnist数据集导出手写体数字图片》中,我们介绍了如何通过TensorFlow将mnist手写体数字集导出到本地保存为bmp文件。 车牌...