Python核心

2022-07-19  本文已影响0人  kimcastle
模块 Module
"""
    Python 核心 - 模块 - 3种调用方式
"""
# 第一种导入方式, As: 模块别名
import module01 as m01

m01.fun01()
cls01 = m01.Class01()
cls01.fun02()

# 第二种导入方式
from module01 import Class01, fun01

Class01.fun02()
fun01()

# 第三种导入方式
from module01 import *

Class01.fun02()
fun01()
"""
练习02: Python 核心 - 模块 - 隐藏成员不能被 from import * 导入
"""
from module02 import *

fun01()
# 隐藏成员(单下划线开头) 不能被 from import * 导入
_fun02()  # name '_fun02' is not defined

# 查看当前文档注释
# 练习02: Python 核心 - 模块 - 隐藏成员不能被 from import * 导入
print(__doc__)
# 查看当前文档绝对路径
# C:/Users/xxx/python/day01/main/exercise02.py
print(__file__)
# 主模块叫做: __main__
# 非主模块叫做:真名
print(__name__)  # __main__
# 作用1: 不是主模块不执行。(测试代码)
# 作用2: 只有主模块才执行
# 使用:  if __name__ == "__main__":
隐藏成员 只有在主模块测试时,才会运行
限制只有从当前模块才能运行
内置模块 time
# 获取当前时间戳
timestamp = time.time()
print(timestamp)  # 1652175860.618811

# 获取当前时间元组
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=10, tm_hour=17, tm_min=47, tm_sec=22, tm_wday=1, tm_yday=130, tm_isdst=0)
tuple_time = time.localtime()
print(tuple_time)
# 时间戳转元组
tuple_time = time.localtime(timestamp)
print(tuple_time)
# 元组转时间戳
timestamp = time.mktime(tuple_time)
print(timestamp)  # 1652177292.0
包 Package

包 package
---模块 module
--------.....
--------.....

# from 包.模块 import 成员变量 as 别名
# from 包.包.模块 import 成员变量 as 别名
# from common.list_helper import list_skill as ls
from skill_system.skill_deployer import list_deployer

# ls()
list_deployer()
异常处理 Error

在 python 中异常(Exception)是总的错误处理父类,其他的个种类型错误 都是它的子类。例如 ValueError 、 NotImplementError 等等......
在 python 中错误就以一种异常, Exception 是错误基类

"""
练习05: Python 核心 - 异常处理完整流程
"""


def div_zero():
    person_count = int(input("请输入人数:"))
    res = 10 / person_count
    print("每个人分得%d个苹果" % res)


try:
    div_zero()
except ValueError:
    print("值错误")
except ZeroDivisionError:
    print("不能为:0")
except:
    print("未知错误")
else:
    print("没有错误,执行...")
finally:
    print("有没错误,都执行...")

"""
练习05: Python 核心 - 异常处理完整流程
"""


class AttackError(Exception):

    def __init__(self, message, error_line, attack_value, error_no):
        self.message = message
        self.error_line = error_line
        self.attack_value = attack_value
        self.error_no = error_no


class Enemy:

    def __init__(self, name, atk):
        self.name = name
        self.atk = atk

    @property
    def atk(self):
        return self.__atk

    @atk.setter
    def atk(self, value):
        if 0 <= value <= 100:
            self.__atk = value
        else:
            raise AttackError("攻击力范围出错", 27, value, 1001)


try:
    enemy = Enemy('luk', 888)
except AttackError as e:
    print(e.message)
    print(e.error_no)

迭代,可迭代对象

例如: List 对象都是可迭代对象 Iterable
list01 = [3,44,43,5,45]

1.获取迭代器 iterator = list01.iter()
2.循环获取下一个元素 iterator.next()
3.遇到异常停止迭代 raise StopIteration
小结:for 循环对象(iterable)必须具有 iter() 方法,并且 iter() 方法必须返回一个迭代器,因为迭代器(iterator) 具有 next() 方法

# 1.获取迭代器
iterator = list01.__iter__()
# 2.循环获取下一个元素
while True:
    try:
          item = iterator.__next__() 
    except StopIteration:
          break  # 3.遇到异常停止迭代
dict_list = {"apple": 100, "banana": 50, "pear": 80}
iterator = dict_list.__iter__()
while True:
    try:
        key = iterator.__next__()
        num = dict_list[key]
        print("%s的数量为:%d" % (key, num))
    except StopIteration:
        break
"""
练习16: Python 核心 - 迭代器 Iterator
"""


class Skill:
    def __init__(self):
        pass


class SkillIterator:
    def __init__(self, target):
        self.__target = target
        self.__index = 0

    def __next__(self):
        if self.__index > len(self.__target) - 1:
            raise StopIteration
        temp = self.__target[self.__index]
        self.__index += 1
        return temp


class SkillManager:
    def __init__(self):
        # 私有变量当做容器用
        self.__skills = []

    def add_skill(self, skill):
        # 添加另外一个类对象进容器
        self.__skills.append(skill)

    def __iter__(self):
        # 本来作为一个容器,可迭代,就必须具有迭代方法 __iter__()
        # 可迭代对象必须返回迭代器
        # 可以在一个方法内 New 另外一个类,把自己类的部分数据交给新类去处理,“指鹿为马,指桑骂槐,张冠李戴”
        return SkillIterator(self.__skills)


manager = SkillManager()
manager.add_skill(Skill())
manager.add_skill(Skill())
manager.add_skill(Skill())

# 一用到 for 循环,想到2点,一是具有 __iter__() 方法,具有 __iter__() 就是
# 可迭代对象,可迭代对象一定返回迭代器 (iterator), 迭代器具有迭代功能 __next()__方法
# 最后 for 具有处理异常的能力
for item in manager:
    print(item)

迭代器设计思想
"""
练习10: Python 核心 - 迭代器原理
# 定义 MyRange类,实现 for 功能
"""


class RangeIterator:
    def __init__(self, target):
        self.__target = target
        self.__index = 0

    def __next__(self):
        if self.__index > self.__target - 1:
            raise StopIteration
        temp = self.__index
        self.__index += 1
        return temp


class MyRange:
    def __init__(self, end=0):
        self.end = end

    def __iter__(self):
        return RangeIterator(self.end)


my = MyRange(4)
for item in my:
    print(item)
"""
练习10: Python 核心 - 迭代器原理 - yield 代替 XxxIterator 迭代器
"""


class MyRange:
    def __init__(self, end=0):
        self.end = end

    def __iter__(self):
        number = 0
        while number < self.end:
            # yield 作用,将这部代码改为迭代器
            yield number
            number += 1


my = MyRange(10)
iterator = my.__iter__()
while True:
    try:
        el = iterator.__next__()
        print(el)
    except StopIteration:
        break

"""
练习10: Python 核心 - 迭代器原理 - 整个迭代类都取代了
"""


# 生成器 = 可迭代对象 + 迭代器
def my_range(stop_value):
    number = 0
    while number < stop_value:
        # yield 作用,将这部代码改为迭代器
        yield number
        number += 1


my01 = my_range(10)
print(my01)  # <generator object my_range>
for item in my01:
    print(item)

生成器原理
生成器表达式
生成器原理与推导式的不同处
"""
练习17: Python 核心 - 生成器练习
"""
list01 = [3, "6", 68, True, 3.4, "str_222"]


# 生成器函数
def num(target):
    for item in target:
        if type(item) == int:
            yield item


for i in num(list01):
    print(i)  # 3   68

# 生成器表达式
re = (item for item in list01 if type(item) == str)
for it in re:
    print(it)  # “6” “str_222”

# 列表推导式
re = [item for item in list01 if type(item) == float]
print(re)  # [3.4]

函数式编程

函数式编程思想

"""
练习21: Python 函数式编程思想 1
列表 [43,4,5,5,6,7,87]
需求1:查找列表中的偶数
需求2:查找列表中大于10的数
需求3:查找列表中所有在范围 10 ~ 50 的数
"""


# 封装(分而治之,变则疏之),封装是一种思想,就是找不同。
def condition01(item):
    return item % 2 == 0


def condition02(item):
    return item > 10


def condition03(item):
    return 10 <= item <= 50


# 继承 (隔离变化) condition 就是“变化”的“代表”,是“可继承”的。
def find_list(condition):
    list01 = [43, 4, 5, 5, 6, 7, 87]
    for item in list01:
        # 具体的实现,则是代表着“多态”
        if condition(item):
            yield item


for i in find_list(condition01):
    print(i)

高阶函数

函数的参数或返回值为函数,就叫做“高级函数”

内置高级函数

(1)map(函数,可迭代对象)
(2)filter(函数,可迭代对象)
(3)sorted(可迭代对象,key=函数,reverse=bool)
(4)max(可迭代对象,key=函数)
(5)min(可迭代对象,key=函数)
闭包
作用:能让逻辑连续

上一篇 下一篇

猜你喜欢

热点阅读