022-2018-1008 random, collections, time, queue

1.今日内容大纲

一. 回顾上周内容
    面向对象:
        对象: 万事万物皆为对象.  特征, 动作或功能放在一起的就是一个对象
        对象如何创建的. 在python中对象是通过类来创建的. 类是对对象的描述.统称.约束.
        class Car:
            def fly(self):
                pass

        类与对象的关系:
            类是类型, 类别. 对事物的描述
            对象是个体. 具体的某一个东西或者事物

            创建对象:
                类名()  实例化.

        三大特征:
            1. 封装. 将数据或者方法封装在一个类中.
            2. 继承. 子类可以自动有用父类中除了私有内容外的所有内容. 包括了抽象方法
            3. 多态. python原生就是多态. 同一个对象, 多种形态.


        成员:
            1. 变量
                实例变量. 对象拥有的东西.
                类变量. 类拥有的东西.多个对象共享. 最好是类名访问类变量
            2. 方法
                1. 实例方法   def 方法(self):pass
                    self: 当前调用这个方法的对象.
                2. 静态方法   最好是类名访问
                    @staticmethod
                    def 方法():
                3. 类方法  最好是类名访问
                    @classmethod
                    def 方法(cls):
            3. 属性
                用方法来描述属性信息

                @property
                def age(self):
                    return 18
        类与类之间的关系:
            1. 依赖关系     类与类的关系是最弱的
                在方法的参数中传递其他类的对象

            2. 关联关系. 组合. 聚合  关系很紧密.
                把一个对象装在自己身上

                class Phone:
                    def __init__(self, person):
                        self.owner = person
                        self.user = user

                class Person:
                    pass

                class User:
                    pass

            3. 继承关系, 实现关系
               class 子类(父类):
                    pass
               父类: 基类. 超类
               子类: 派生类.

               实现关系:
                    父类: 抽象类.  如果都是抽象方法. 父类被称为: 接口
                    子类: 必须对父类中的抽象方法进行重写.
               约束:
                   父类对子类的约束. 子类必须重写的内容
                   1. 抛异常 raise NotImplementError
                   2. 抽象类
                        from abc import ABCMeta, abstractmethod
                        元类必须设置成ABCMeta。 metaclass = ABCMeta
                        这个类中就可以写出抽象方法。 @abstractmethod
                        类中包含抽象方法。 那么这个类就是抽象类.  抽象类一般不创建对象

               MRO:
                    1. 经典类
                        采用的是深度优先遍历
                    2. 新式类
                        如果没有菱形继承. 就是深度优先遍历。
                        如果是简单的菱形继承。把头干掉。 使用深度优先。 最后是头
                        如果是复杂的菱形.需要用C3算法
                        找到每个类的继承关系. 然后拆分. 拆到最后. 然后再合并.

                        笔试题. 第一件事先画图. 看有没有菱形. 然后再算.
               super:
                    执行MRO列表中的下一个类中的方法
                    super().方法()
                    super(类名, self).方法()

            反射
                hasattr(obj, str)
                getattr(obj, str)
                setattr(obj, str, value)
                delattr(obj, str)

            issubclass, type, isinstance
                issubclass: 判断是否是xxx的子类
                type: 精准的给出对象是哪个类的对象
                isinstance: 判断xxx是否是xxx类型的.

            方法和函数
                FunctionType, MethodType

            异常处理:
                抛出异常: raise Exception()
                捕获异常:
                    try:
                        xxxx
                    except Exception as e:
                        xxxx
                    else:

                    finally:

                堆栈信息:
                    import traceback
                    和logging一起用

                自定义异常: 继承Exception

二. 作业

三. 今日主要内容
    1. collections
        
    2. queue队列 stack栈

    3. time

    4. random

    5. os, sys

    序列化

2.模块

class Animal:
    pass

from collections import Iterable, Iterator
lst = []
print(isinstance(lst, Iterable))   #  True
print(isinstance(lst, Iterator))   # False

3.collection.py


# 计算字符串中每个字符出现的次数
s = "abcdefadsfasfasdfbadsfasdbfdasfdas" # 可迭代
dic = {}
for c in s:
    dic[c] = dic.get(c, 0) + 1
print(dic)

from collections import Counter # 引入模块, 计数器
c = Counter(s)  # 创来和字典差不多

lst = ["周杰伦", '周杰伦', "王力宏", "大阳哥", "大阳哥", "刘伟", "刘伟"]
c = Counter(lst)
print(c)建一个Counter对象
print(c)
print(c['s']) # 用起



from collections import deque
d = deque()  # 创建双向队列
d.append("李茶的姑妈") # 默认在右侧添加
d.append("无双")
d.append("影")
d.append("找到你")
#让悲伤逆流成河, 理查的姑妈, 无双, 影, 找到你
print(d)
d.appendleft("让悲伤逆流成河") # 左侧添加
print(d)


print(d.pop()) # 从右边删除
print(d.pop()) # 从右边删除
print(d.popleft()) # 从左边删除
print(d.pop()) # 从右边删除
print(d)


from collections import namedtuple

po = namedtuple("Point", ["x", "y"]) # 定义了简单的类-lambda
p = po(1, 2) # 命名元组
print(p)

class Point:
    def __init__(self,x, y):
        self.x = x
        self.y = y
p = Point(1, 2)

py3.6以上使用的是新算法. 来自于pypy. 节约20-30%内存
d = {"a":1,"b":2,"c":3}
print(d)

from collections import OrderedDict
od = OrderedDict({"a":1,"b":2,"c":3})
print(od.get("b"))
print(od["b"])


from collections import defaultdict
d = defaultdict(list) # {} list() 必须是callable
d['刘伟'] = "奥特曼"
print(d['大阳哥']) # 当key不存在的时候. 返回默认值.其实就是callable()
print(d['刘伟'])

# 11 22 33 44 55 66 77 88 99
lst = [11, 22, 33, 44, 55, 66, 77, 88, 99]
dic = {}
for el in lst:
    if el > 66:
        dic.setdefault("key1", []).append(el)
    else:
        dic.setdefault("key2", []).append(el)
print(dic)

lst = [11, 22, 33, 44, 55, 66, 77, 88, 99]
dd = defaultdict(list)
for el in lst:
    if el > 66:
        dd['key1'].append(el)
    else:
        dd['key2'].append(el)
print(dd)






4.栈和队列


# 队列: 先进先出.  First In First Out FIFO
# 栈: 先进后出. First In Last Out FILO
import queue
# q = queue.Queue() # 创建队列
# q.put("刘伟") # 放入元素
# q.put("大阳哥")
# q.put("吴佩琪")
#
# print(q.get())  # 获取元素
# print(q.get())
# print(q.get())
# print(q.get()) # 阻塞了. 在等下一个元素, input()

# 装馒头的桶
# 1. 入栈
# 2. 出栈
# 属性:   1. 列表(容器) 2.大小(size) 3. 栈顶指针(下一个装元素的位置)
class StackFullError(Exception):
    pass
class StackEmptyError(Exception):
    pass
class Stack:
    def __init__(self, size):
        self.index = 0  #  栈顶指针
        self.size = size
        self.lst = []  # 容器

    def push(self, el):
        if self.index < self.size:  #  还没有装满
            self.lst.insert(self.index, el)
            self.index += 1
        else:   # 装满了
            raise StackFullError("the stack is full!")

    def pop(self):
        if self.index > 0:
            self.index -= 1
            return self.lst[self.index]
        else:
            raise StackEmptyError("the stack is empty!")

# 使用
# 1.实例化栈
s = Stack(5)
s.push("馒头1")
print(s.pop())
s.push("馒头2")
print(s.pop())
s.push("馒头3")
print(s.pop())
s.push("馒头4")
print(s.pop())
s.push("馒头5")
print(s.pop())
s.push("馒头6")
print(s.pop())

5.time模块

import time
print(time.time()) # 当前系统时间 1538970854.5946708 float 时间戳. 给机器用的.数据库有的时候存储的是时间戳
# 以 1970-01-01 00:00:00 原点. 每一秒一个数字.

# 时间格式 格式化时间
print(time.strftime("%Y/%m/%d %H:%M:%S")) # 给人看的.

# 结构化时间
print(time.localtime())  # 用来计算的.


# 18888888888 时间戳 -> 格式化时间
# 把时间戳转化成结构化时间
f = 18888888888
st = time.localtime(f)
print(st)
# 格式化结构时间
t = time.strftime("%Y/%m/%d %H:%M:%S",st) # f: format 格式化
print(t)

# 用户输入了一个时间 2018-09-08 11:22:36   - 存储 时间戳
# 先把格式化时间转化成结构化时间
s = "2018-09-08 11:22:36"
st = time.strptime( s , "%Y-%m-%d %H:%M:%S") # p:parse 转换
t = time.mktime(st) #  转化成时间戳 1536376956
print(t)


# 时间差的计算.1. 用自己的办法解决问题. 2. 看我的那个代码.  研究.

print(time.asctime())


6.random模块

import random

print(random.random()) #  0-1小数  想办法完成[1,100]之间的随机整数
print(random.uniform(1, 3)) # 1-3之间的小数

print(random.randint(1, 36)) # [1,36]随机整数
print(random.randrange(1, 5, 3)) # [1, 5) 步长是3


print(random.choice(["马化腾", ["倚天屠龙记", "天龙八部", "射雕"], "张无忌", "周伯通", "刘伟"])) # 随机选一个
print(random.sample(["刘伟", "大阳哥", "大猪蹄子", "胡辣汤"], 3))
print(random.sample(list(range(1,37)), 7))


lst = [1,2,3,4,5,5,6,7,8,9,]
random.shuffle(lst) # 洗牌
print(lst)

7.os模块

# import os

# 创建多级目录
os.makedirs("a/b/c/d/e/f/g")
os.removedirs("a/b/c/d/e/f/g") # 空目录可以删除. 非空的不能删

os.system("dir") # 执行命令
ret = os.popen("dir").read() # 执行命令返回结果
print(ret)

print(os.getcwd())

print(os.path.split(r"D:\python学院\s16\第一阶段\day08 文件操作\video"))
print(os.path.exists(r"D:\python学院\s16\第一阶段\day08 文件操作\video12312312312321"))





print(os.name)  # nt NT windows平台

import sys
# print(sys.version)
print(sys.path) # 获取系统搜索模块的路径
sys.path.clear() # 应该是没了的.
import os
print(os.name)

# sys.platform = "刘伟"
print(sys.platform)
import sys

print(sys.argv)  # 在运行的时候给python传递的信息.
ip = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]

print(ip)
print(username)
print(password)


8.其他补充

# start.bat

python36 "07 os模块.py" 127.0.0.1 root 123456
pause

9.小试牛刀

1、回顾文件递归遍历. 默写一遍.
 入口在:  当文件是个文件夹的时候
出口在: 文件是一个文件

2、写一个copy函数,接受两个参数,第一个参数是源文件的位置,第二个参数是目标位置,将源文件copy到目标位置。

3、计算时间差(用户输入起始时间和结束时间. 计算时间差(小时), 
 		例如, 用户输入2018-10-08 12:00:00   2018-10-08 14:30:00 输出2小时30分

3、使用random.random()来计算[m,n]以内的随机整数


5、使用os模块创建如下目录结构
# glance
# ├── __init__.py
# ├── api
# │   ├── __init__.py
# │   ├── policy.py
# │   └── versions.py
# ├── cmd
# │   ├── __init__.py
# │   └── manage.py
# └── db
#      ├── __init__.py
#      └── models.py

 6. 写一个用户注册登陆的程序,每一个用户的注册都要把用户名和密码用字典的格式写入文件userinfo。在登陆的时候,再从文件中读取信息进行验证。




明日默写内容:

1. 时间戳转换成格式化时间
2. 格式化时间转换成时间戳

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值