python学习_day4--面向对象、闭包、异常、文件、随机数

面向对象继承

"""
继承:提高代码重用率
子类:继承的
父类:被继承的、基类、超类
所有的类都继承自object类
格式:类名.__bases__
"""
import math

class Animal:
    def eat(self):
        print("吃------")

    def sleep(self):
        print("睡---")

class Dog(Animal):  # 要继承的父类名字
    def bite(self):
        print("可能会咬人-----")

class Cat(Animal):
    def climb_tree(self):
        print("爬树------")

d1 = Dog()
d1.eat()

print("DOG的父类", Dog.__base__)
print("Animal的父类", Animal.__base__)

# 形状类
# 圆类、正方形类

class Shape:
    def __init__(self, *p):
        self.p = p

    def area(self):
        pass

class Circle(Shape):
    def area(self):
        print("self.p----------", self.p, self.p[0])
        print("圆的面积是", math.pi * self.p[0] ** 2)

class Square(Shape):
    def area(self):
        print("正方形的面积是", self.p[0] ** 2)

c1 = Circle(1)
c1.area()

s1 = Square(2)
s1.area()

# 矩形 rect w,h

# t1 = (2, 3)
# w,h = t1
# print(w, h, type(w))

class Shape:
    def __init__(self, p):
        self.p = p

    def area(self):
        pass

class Circle(Shape):
    def area(self):
        print("圆的面积是", math.pi * self.p ** 2)

class Square(Shape):
    def area(self):
        print("正方形的面积是", self.p ** 2)

class Rect(Shape):
    def __init__(self, w, h):
        # super(Rect, self).__init__(w)
        super().__init__(w)
        # self.p = w
        self.p1 = h

    def area(self):
        print("矩形形的面积是", self.p * self.p1)

print('-' * 70)

class Student:
    def task(self):
        print("上课")
        print("写作业")

class Monitor(Student):
    def task(self):
        super(Monitor, self).task()
        print("收作业")

m1 = Monitor()
m1.task()

# r1 = Rect(2, 3)
# r1.area()

多继承

class A:
    def run(self):
        print("A在运行")

class B:
    def run(self):
        print("B在运行")

class C(A, B):  # 顺序代表了继承先后顺序
    pass

c1 = C()
c1.run()

print("继承顺序", C.__mro__)

多态

"""
def fun(父类类名):

fun(子类1对象)---
fun(子类2对象)

"""

class Pay:
    def pay(self):
        pass

class AliPay(Pay):
    def pay(self):
        print("支付宝支付")

class AppPay(Pay):
    def pay(self):
        print("APP store 支付")

def consumptio(Pay):
    Pay.pay()

ali = AliPay()
consumptio(ali)

app = AppPay()
consumptio(app)

class WeixinPay:
    def pay(self):
        print("微信支付----")

wxpay = WeixinPay()
consumptio(wxpay)

闭包

"""
在python中创建一个闭包一般有3个要求:
1.闭包函数必须有内嵌函数。
2.内嵌函数必须要引用外层函数的变量。
3.闭包函数返回内嵌函数的地址(函数名称)
"""
import time

def outer():
    name = "张三"

    def inner():
        # print(name)
        print("哈哈哈")

    return inner

f = outer()  # ---返回为内嵌函数的地址
f()

# 查看该函数是否为闭包
print(f.__closure__)  # 返回地址,表示为闭包; 返回None  不是闭包


# 装饰器
# 在不改变原函数参数,以及调用的方式。对原函数进行扩展

def fun():
    print("hahahah")
    time.sleep(5)

# 测试函数的耗时
# 方式1
# start = time.time()
# fun()
# end = time.time()
# print("运行时长", end-start)

# 方式2:在函数定义内部增加计时代码块

print('-' * 70)

# 扩展代码在前
def timer(fun):
    def inner():
        start = time.time()
        print("函数前的扩展")
        fun()
        print("函数后的扩展")
        end = time.time()
        print("运行时间", end - start)

    return inner

@timer  # 语法糖
def fun():
    print("hahahah")
    # time.sleep(5)

# fun = timer(fun)
fun()

def wraper1(fun):
    def inner():
        print("before 1----------")
        fun()
        print("After 1----------")

    return inner

def wraper2(fun):
    def inner():
        print("before 2----------")
        fun()
        print("After 2----------")

    return inner

@wraper2
@wraper1
def f():
    print("基本的函数")

f()

异常

"""
异常 语法正确的情况下,程序运行错误
"""
try:
    print(1 / 1)
    l1 = [1, 2, 3, 4]
    print(l1[0])
    print(b)
except ZeroDivisionError:
    print("除0错误")
except IndexError:
    print("索引越界")
except:
    print("其他错误")
finally:
    print("无论是否有异常都会输出")

# try:
#     print(1 / 0)
#     l1 = [1, 2, 3, 4]
#     print(l1[100])
#     print(1 > "aa")
# except:
#     print("运行错误")


name = input("enter your name:")
try:
    if len(name) < 3:
        raise Exception("长度过短")
    else:
        print("姓名是", name)
except:
    print("重新输入")

文件

"""
文本文件:txt
二进制文件
打开文件 open
读写文件 read/write
关闭文件 close
"""
import time
import os

# file 文件路径,
# mode 打开文件的模式。是读还是写?默认r (read)
# encoding
# f = open("day4_2多继承.py", mode='r', encoding="utf-8")
# f = open("新文件.txt", mode='r', encoding="ANSI")
# content = f.read(3)
# content = f.readline()  # 每次读取一行
# content = f.readlines()  # 读取全部内容,每一行作为列表的一个元素
# print(content)
# f.close()

# for tmp in open("新文件.txt", mode='r', encoding="ANSI").readlines():
#     print(tmp)
#     time.sleep(1)

# 写文件
# 当模式为w,如果文件存在,会将文件原内容覆盖掉。
# 如果文件不存在,会创建文件

# 如果不希望内容被覆盖掉 模式修改为追加 mode='a'
# f = open("新文件.txt", mode='a')
# f.write("当模式为w,如果文件存在,会将文件原内容覆盖掉")
# f.close()

# 可以不用关闭
# with open("新文件.txt", mode='r') as f:
#     for line in f.readlines():
#         line = line.strip("\n").replace("? ?", " ")
#         if line == "":
#             continue
#         print(line)
#         time.sleep(0.1)

# mkdir 只能创建一级路径
# os.mkdir("file/dir1/dir2/")

# makedirs 创建多级目录
os.makedirs("file/dir1/dir2/", exist_ok=True)

path = "D:\pycharm\projict\day4"
file_name = "文本文件.txt"

full_path = path + file_name
print("路径合并后1", full_path)
# 路径拼接推荐使用方式
full_path = os.path.join(path, file_name)
print("路径合并后2", full_path)

with open(full_path, mode='w') as fw:
    fw.write("让我们荡起双桨 小船儿推开波浪bai 海面倒映着美丽的白塔")

print('-' * 70)
# 获取某路径下所有文件
path = "D:\pycharm\projict\day4"
print(os.listdir(path))

随机数

# encoding:utf-8
import random
import string

l1 = ["石头", "剪刀", "布", 4]
# l1 = ["aa", "bb"]
# random.choice 从数值
print(random.choice(l1))

# 生成验证码(共4位数,包含字母和数字)

code = [1, "a", "A", "c"]
code = [str(tmp) for tmp in code]
# 将列表中的元素 按照一定的形式连接 为 一个字符串
res = "_".join(code)
print(res)

print(string.ascii_letters)
print(string.digits, type(string.digits))

print(ord("A"))

猜你喜欢

转载自blog.csdn.net/weixin_45800653/article/details/121407884