python基础学习之二

一、Python中的类

1、类的创建

  • 用关键词class来创建,模式:**关键词 类的名称:**例如:class student:
  • 注意:
    (1)init():是类的初始化方法,创建一个类的实例时就会调用一次这个方法。
    (2)self:代表类的实例,在定义类的方法时必须要有的,但是在调用时不必传入参数。
  • 实例:
Class student;
    student_Count = 0
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
        Student.student_Count += 1
        
    def dis_student(self):
        print("Student name:",self.name, "Student age:",self.age)
    
    student1 = Student("Tang", "20")
    student2 = Student("Wu", "22")
    
    student1.dis_student()
    student2.dis_student()
    print("Total Student:", Student.student_Count)
输出:
Student name:Tang Student  age:20
Student name:Wu Student  age:22
Total Student:2

2、类的继承

  • 当一个类被继承时,这个类中的类初始化方法是不会被自动调用的,需要在子类中重新定义类的初始化方法。
  • 实例
Class People:
     def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def dis_name(self):
        print("name is: ", self.name)
        
    def dis_age(self, age):
        print("age is: ", self.age)
        
    def dis_age(self):
        print("age is:", self.age)
        
Class Student(People):
    def __init__(self, name, age, school_name):
        self.name = name
        self.age = age
        self.school_name = school_name
        
    def dis_student(self):
        print("school name is:", self.school_name)
        
student = Student("Wu", "20", "GLDZ") #创建一个Student对象
student.dis_student() #调用子类的方法
student.dis_name() #调用父类的方法
student.dis_age()  #调用父类的方法
student.set_age(22)  #调用父类的方法
student.dis_age()    #调用父类的方法
输出:
school name is:GLDZ
name is:Wu
age is:20
age is:22

3、类的重写

  • 在继承一个类后,父类中的很多方法也许不能满足我们现有的需要,这就需要对类进行重写。
  • 实例:

在这里插入图片描述

输出:
This is Child。

二、NumPy

1、NumPy是一个高性能的科学计算和数据分析基础包,提供数组和矩阵的便捷计算方法。
2、创建多维数组
使用np.array()方法,

x = np.array([1.0, 2.0, 3.0])  
print(x)
[ 1. 2. 3.] 

2、多维数组常用属性
(1)ndim:返回维度的数量,即二维、三维…

a = np.ones([2,3])  #创建全1的数组
a.ndim   #输出结果:2

(2)shape:返回数组的维度值,比如二维数组返回的结果为(n,m)。用法:例如:a.shape
(3)size:返回数组中的元素的总数量
(4)dtype:返回数组中的元素的数据类型。

a = np.ones([2,3])  #创建全1的数组
a.dtype   #输出:dtype('float64')

3、多维数组的基本操作
(1)算术运算

  • 相同形状的多维数组可进行加减乘除算法运算,也可直接和标量进行算术运算(也称为广播),但是矩阵不可以。
  • 矩阵算术和数组的存在不同,矩阵不存在除法运算,但是数组可以;数组的乘法运算是通过将对应位置的元素相乘来完成的,而矩阵不是,看下面实例说明。
import numpy as np

a = np.array([1,2,3])
b = np.array([4,5,6])

#数组的乘法运算
print("a * b = ", a*b)  #a * b =  [ 4 10 18]

#矩阵的乘法运算
c = a.dot(b)
print("Matrix1: a * b = ", c)  #Matrix1: a * b =  32
d = np.dot(a,b)
print("Matrix2: a * b = ", d)  #Matrix2: a * b =  32

4、数组的自身运算
(1)min/max:找出数组中所有元素中值最小/大的元素,可以通过设置axis的值来按行或按列查找元素中的最小值,a.mim(),a.max()。
(2)sum:对所有元素进行求和运算。
(3)exp:对数组中所有元素进行指数运算。
(4)sqrt:对数组中的所有元素进行平方根运算。
(5)square:对数组中的所有元素进行平方运算。

三、Matplotlib

1、Mataplotlib定位于数据的可视化展现,集成了很多数据可视化方法,常用的方法有:

  • 线型图
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
x = np.random.randn(30)
plt.plot(x, "r--o")
plt.show()

在这里插入图片描述

  • 线条颜色、标记形状和线型。线条颜色的常用参数有“b”(蓝色)、“g”(绿色)等等,标记形状:“o”(圆形)、“*” ( *符号)等等、线型线条形状“-”(实线)、“–”(虚线)等等。
import matplotlib.pyplot as plt
import numpy as np

a = np.random.randn(30)
b = np.random.randn(30)
c = np.random.randn(30)
d = np.random.randn(30)
plt.plot(a, "r--o", b, "b-*", c, "g-.+", d, "m:x") #"-."(点实线)、":"(点线)
plt.show()

在这里插入图片描述

  • 标签和图例。使图像更容易理解。
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
x = np.random.randn(30)
y = np.random.randn(30)

plt.title("Example")
plt.xlabel("X")
plt.ylabel("Y")
X, = plt.plot(x, "r--o")
Y, = plt.plot(y, "b-*")
plt.legend([X, Y], ["X", "Y"]) #标签和图例的显示代码
plt.show()

在这里插入图片描述

  • 子图(Subplot)。将多个图像同时在不同的位置显示。

import matplotlib.pyplot as plt
import numpy as np

a = np.random.randn(30)
b = np.random.randn(30)
c = np.random.randn(30)
d = np.random.randn(30)

fig = plt.figure()     #定义一个实例,通过fig.add_subplot方
ax1 = fig.add_subplot(2,2,1)  #法向fig实例中添加我们需要的子图
ax2 = fig.add_subplot(2,2,2) 
ax3 = fig.add_subplot(2,2,3)  #前两个数字表示把整块图划分成了两行两列,一共4张
ax4 = fig.add_subplot(2,2,4)  # 子图,最后1个数字表示具体使用哪一张子图进行绘制。

A, = ax1.plot(a, "r--o")
ax1.legend([A], ["A"])
B, = ax2.plot(b, "b-*")
ax2.legend([B], ["B"])
C, = ax3.plot(c, "g-.+")
ax3.legend([C], ["C"])
D, = ax4.plot(d, "m:x")
ax4.legend([D], ["D"])
plt.show()

在这里插入图片描述

  • 散点图(Scatter),展示所有数据的分布和布局。核心代码时plt.scatter(x,y, c = “g”, marker =
    “o”, label"(X, Y)"),三个重要参数:“c”:指定参数点颜色;“marker”:形状;“label”:使用的图例。
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
x = np.random.randn(30)
y = np.random.randn(30)

plt.scatter(x,y, c = "g", marker = "o", label = "(X, Y)")  #参数点为绿色,圆点
plt.title("Example")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend(loc = 1)  #强制图例在图中的右上角,loc=0:最好的位置,
plt.show()           #loc=2:左上角,loc=3:左下角,loc=4:右上角

在这里插入图片描述

  • 直方图(Histongram,质量分布图)
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
x = np.random.randn(1000)
plt.hist(x, bins = 20, color = "g")   #bins用于指定我们绘制的直方图条纹的数 量。
plt.title("Example")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

在这里插入图片描述

  • 饼图,绘制饼图的核心代码为
    plt.pie(sizes, explode=(0, 0, 0.1), labels=labels, autopct=’%1.1f%%’, startangle=60)

sizes= [15, 50, 35] 的三个数字确定了每部分数据系列在整个圆形中的占比;
explode定义每部分数据系列之间的间隔,如果设置两个0和一个0.1,就能突出第3部分;
autopct其实就是将 sizes中的数据以所定义的浮点精度进行显示;
startangle是绘制第1块饼图时该饼图与X轴正方向的夹角度数,这里设置为90,默认为0;

plt.axis(‘equal’) 是必不可少的,用于使X轴和Y轴的刻度保持一致,只有这样,最后得到饼图才是圆形的

import matplotlib.pyplot as plt

labels = ['Dogs', 'Cats', 'Birds']
sizes = [15, 50, 35]

plt.pie(sizes, explode = (0,0,0.1), labels = labels,
        autopct = '%1.1f%%', startangle = 90)
plt.axis('equal')
plt.show()

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值