【第20天】Python第一阶段学习总结
2021/10/15
一. 面向对象编程–代码的复用
1. 方法一:继承
- 通过继承来是实现对已有代码的复用
- object是所有类的父类
class MyList(list):
"""自定义列表"""
def __init__(self, *args):
super().__init__()
for value in args:
self.append(value)
def append(self, value):
if not isinstance(value, (int, float)):
raise ValueError('只能追加int或float类型的元素')
super().append(value)
def insert(self, index, value):
if not isinstance(value, (int, float)):
raise ValueError('只能插入int或float类型的元素')
super().insert(index, value)
def mean(self):
"""均值"""
return sum(self) / len(self)
def median(self):
"""中位数"""
length = len(self)
sorted_list = sorted(self)
if length % 2:
return sorted_list[length // 2]
return (sorted_list[length // 2 - 1] + sorted_list[length // 2]) / 2
def std(self):
"""标准差(standard deviation)"""
return self.var_s() ** 0.5
def var_s(self):
"""样本方差(sample variance)"""
x_bar = self.mean()
return sum([(x - x_bar) ** 2 for x in self]) / (len(self) - 1)
nums = MyList(1, 2, 3, 4, 5)
print(nums)
nums.append(8)
nums.insert(0, 7)
print(nums)
nums += [8, 12, 15]
print(nums)
print(sorted(nums))
print('均值:', nums.mean())
print('中位数:', nums.median())
print('方差:', nums.var_s())
print('标准差:', nums.std())
2. 方法二:委派关系
- 通过委派关系(关联关系)实现对象代码的复用
class ThyList:
def __init__(self, *args):
self.container = []
for value in args:
self.append(value)
def append(self, value):
if not isinstance(value, (int, float)):
raise ValueError('只能追加int或float类型的元素')
self.container.append(value)
def insert(self, index, value):
if not isinstance(value, (int, float)):
raise ValueError('只能插入int或float类型的元素')
self.container.insert(index, value)
def mean(self):
"""均值"""
return sum(self.container) / len(self.container)
def median(self):
"""中位数"""
length, sorted_list = len(self.container), sorted(self.container)
if length % 2 != 0:
return sorted_list[length // 2]
return (sorted_list[length // 2 - 1] + sorted_list[length // 2]) / 2
def std(self):
"""样本标准差(standard deviation)"""
return self.var() ** 0.5
def var(self):
"""样本方差(variance)"""
x_bar = self.mean()
return sum([(x - x_bar) ** 2 for x in self.container]) / (len(self.container) - 1)
def __repr__(self):
return self.container.__repr__()
nums = ThyList(1, 2, 3, 4, 5)
print(nums)
nums.append(100)
nums.insert(0, 200)
print(nums)
print('均值:', nums.mean())
print('中位数:', nums.median())
print('方差:', nums.var())
print('标准差:', nums.std())
二. 三方库的应用
1. PyQt5
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
def close_window():
reply = QMessageBox.question(window, 'Message',
"Are you sure to quit?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
app.quit()
app = QApplication(sys.argv)
window = QWidget()
window.resize(1000, 800)
window.setWindowTitle('My First App')
button = QPushButton('Hit Me!', window)
button.setToolTip('这是一个按钮')
button.resize(100, 30)
button.move(100, 100)
button.clicked.connect(close_window)
window.show()
sys.exit(app.exec())
2. pyecharts
from pyecharts.charts import Bar
bar = Bar()
bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.add_yaxis("商家B", [15, 21, 13, 55, 32, 90])
bar.render('sales.html')
import pyecharts.options as opts
from pyecharts.charts import Pie
x_data = ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"]
y_data = [335, 310, 274, 235, 400]
data_pair = [list(z) for z in zip(x_data, y_data)]
data_pair.sort(key=lambda x: x[1])
print(data_pair)
(
Pie(init_opts=opts.InitOpts(width="1600px", height="800px", bg_color="#2c343c"))
.add(
series_name="访问来源",
data_pair=data_pair,
rosetype="radius",
radius="55%",
center=["50%", "50%"],
label_opts=opts.LabelOpts(is_show=False, position="center"),
)
.set_global_opts(
title_opts=opts.TitleOpts(
title="Customized Pie",
pos_left="center",
pos_top="20",
title_textstyle_opts=opts.TextStyleOpts(color="#fff"),
),
legend_opts=opts.LegendOpts(is_show=False),
)
.set_series_opts(
tooltip_opts=opts.TooltipOpts(
trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
),
label_opts=opts.LabelOpts(color="rgba(255, 255, 255, 0.3)"),
)
.render("customized_pie.html")
)
|