python自定义类实战 - 继承 重写

自定义类实战

  1. 当我们在使用一个列表时如果里面仅仅包含了整数和小数
  2. 那么我们想直接用这个列表获取(平均值,中位数,方差,标准差时)
  3. 而我们的列表又没有这些方法, 那么我们可以自定义我们自己的列表类
  4. 去实现我们想要的这些功能

方法一 - 继承原来的list类丰富他的方法

import math
from functools import reduce


class MyList(list):  # 继承list类

    def __init__(self, *args):
        super().__init__()  # 重写父类的init方法 - 先通过super()调用父类原有的init
        for value in args:
            self.append(value) # 将值全部传到列表中去
        self.check_value() # - 检查输入值中是否有不是整数和小数的值
	
    # 检查值
    def check_value(self):
        for x in self:
            if type(x) not in (int, float):
                raise ValueError('列表中有非整数和小数的值')
        else:
            return self

    def append(self, value):
        if type(value) not in (int, float):
            raise ValueError('不能添加非整数和小数的数')
        else:
            super().append(value)

    @property
    def average(self):
        """求平均"""
        return reduce(lambda x, y: x + y, self, 0) / len(self)

    @property
    def variance(self):
        """总体方差"""
        avg = self.average
        num = reduce(lambda x, y: x + y, [(avg - i) ** 2 for i in self], 0)
        return num / len(self)

    @property
    def std(self):
        """总体标准差"""
        return math.sqrt(self.variance)

    @property
    def median(self):
        """中位数"""
        sorted_list = sorted(self)
        if len(self) % 2:
            return sorted_list[len(self) // 2]
        return (sorted_list[len(self) // 2] + sorted_list[len(self) // 2 - 1]) / 2


myl1 = MyList(1, 2, 3, 4, 5)
print(MyList(2, 4, 6, 8, 10))
print(myl1.average)
myl1.append(6)
print(myl1)
print(myl1.average)
print(myl1.variance)
print(myl1.std)
print(myl1.median)
print(myl1)

方法二:在自定义类中关联list对象,将各种操作委派给list对象来完成,我们也可以通过关联关系实现对象代码的复用。

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('ThyList追加int或float类型的元素')
        self.container.append(value)

    def insert(self, index, value):
        if not isinstance(value, (int, float)):
            raise ValueError('ThyList插入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())

简单使用 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.Yes
    )
    if reply == QMessageBox.Yes:
        app.quit()


app = QApplication(sys.argv)
# 创建一个APP对象

# 窗口创建和设置
window = QWidget()
window.resize(800, 600)
window.setWindowTitle('My First App')

# 添加按钮的设置
button = QPushButton('Hit Me!', window)
button.setToolTip('这是一个按钮')
button.resize(80, 30)
button.move(100, 100)
button.clicked.connect(close_window)

# 显示窗口
window.show()

sys.exit(app.exec())

简单使用 pyecharts

from pyecharts.charts import Bar

bar = Bar()
bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 35, 20])
bar.add_yaxis("商家B", [15, 21, 13, 30, 55, 39])
bar.render('bar.html')
from pyecharts.charts import Pie
from pyecharts import options

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], reverse=True)


pie = Pie(init_opts=options.InitOpts(width='800px', height='400px'))
pie.add(
    series_name='引流渠道', data_pair=data_pair,
    radius=['40%', '60%'], center=['50%', '50%'],
)
pie.set_series_opts(
    label_opts=options.LabelOpts(
        formatter='{b}: {c} ({d}%)'
    )
)
pie.render('pie.html')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

azured_xu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值