19.5.8笔记and作业

写一个单例模式

class Stu():
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,'inst'):
            cls.inst=object.__new__(cls)
        return cls.inst
    def show(self,name):
        self.name=name
zs=Stu('张三')
ls=Stu('李四')
print(zs is ls)
print(zs==ls)

__call__写一个斐波那契数列

class Feibo():
    def __init__(self):
        pass
    def __call__(self,n):
        a,b=1,1
        lb=[]
        if n==1:
            lb.append(1)
        elif n==2:
            lb.append(1)
            lb.append(1)
        else:
            x=1
            while x<=n:
                lb.append(a)
                a,b=b,a+b
                x+=1
        return lb
a=Feibo()
print(a(5))

3.如何销毁一个对象

4.写出__str__的方法

class A():
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
       return '我叫{},今年{}岁'.format(self.name,self.age)
    def __repr__(self):
        return '姓名{},年龄{}'.format(self.name,self.age)
zs=A('张三',19)
ls=A('李四',10)
print('%s'%zs)#调用str
print('%r'%ls)#调用repr,当str不在,默认,调用repr

5.#hash()函数

class A():
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __eq__(self, other):
        return self.__dict__==other.__dict__
    def __hash__(self):
        return hash(self.name)
a=A('张三',19)
b=A('李四',20)
c=A('张三',19)
d={a,b,c}
print(a==c)#True
print(a is c)#False,地址不同
print(d)

issubclass(B,A)判断B是不是A的子类
isintance(c,A)判断c是不是A类的实例

enumerate函数,枚举函数

a='abc'
for x,y in enumerate(a):
    print(x,y)

dir,查看可用的函数

print(dir([].__iter__()))
print(dir({}))
print(dir(()))

#迭代器,就是逐个打印,减少内存占用量

a=[1,3,4]
b=a.__iter__()
print(next(b))
print(b.__next__())

a='123'
b=list(a)
c=tuple(a)
print(c)

用迭代写一个斐波那契数列

class Feibo():
    def __init__(self,num):
        self.num=num
        self.current=1
        self.a=1
        self.b=1
    def __iter__(self):
        return self
    def __next__(self):
        if self.current<=self.num:
            ret=self.a
            self.a,self.b=self.b,self.a+self.b
            self.current+=1
            return ret
        else:
            raise StopIteration#停止迭代
for x in Feibo(5):
    print(x)

生成器,yeild生成器,原理是先停下手上的,去干其他的,再回来

def han():
    i=0
    while i<10:
        yield i
        i+=1
b=han()
print(next(b))
print(next(b))

##eg:

def hanshu():
    yield 1
    yield 2
a=hanshu()
print(next(a))
print(next(a))

##send方法的使用

def bingqilin():
    a=0
    b=yield a
    print('b-----',b)
    yield 2
    yield 3
x=bingqilin()
print(next(x))#0
y=x.send(999)给B赋值999,并且将2赋值给y
print(y)#2
print(next(x))#3

#send方法eg

def jisuan():
    get_num=0
    count=1
    avg=0
    total=0
    while True:
        get_num=yield  avg
        total=total+get_num
        avg=total/count
        count+=1
b=jisuan()
next(b)
print(b.send(10))
print(b.send(20))
print(b.send(30))

eg:

  def qushu():
        for x in 'abc':
            yield x
        for x in range(5):
            yield x
    b=qushu()
    for i in b:
        print(i)

yeild from的使用

def gen():
    yield from 'asf'
    yield from range(3)
for x in gen():
    print(x)

#生成器的表达式

a=[i for i in range(3)]
print(a)#[0,1,2]
c=(i for i in range(3))#生成器表达式
print(c)

装饰器
闭包三要素
1.闭包函数,必须要有嵌套函数
2.内嵌函数,必须要引用外层函数的变量
3.闭包函数返回内嵌函数的地址(函数名称 )

def hanshu1(tax):
    name='张三'
    def hanshu2(a,b):
        c=(a+b)*tax
        return c
    print(hanshu2.__closure__)#判断是不是闭包函数,带有call则是闭包
    return hanshu2
a=hanshu1(0.2)
y=a(5,6)
print(y)#0.2*(5+6)
b=hanshu1(0.3)
z=b(5,6)
print(z)#0.3*(5+6)

装饰器

import time
def hehe(f):
    def haha():
        a=time.time()
        print('11111')
        f()##这句话的意思是,再跳回到修饰的函数,执行完修饰的函数,再执行下面的语句
        b=time.time()
        print('2222222222',b-a)
    return haha
@hehe#这句话意思是用hs这个函数去修饰hehe,所以首先找到呵呵这个函数
def hs():
    print('开始')
    he=0
    for i in range(5):
        he+=1
    print('结束')
hs()
@hehe##(这句话的意思是用hs1去修饰hehe这个函数,所以首先找到hehe这个函数)
def hs1():
    print('iiiiiiiii')
    print('yyyyyyyyy')
hs1()

#eg:

def decor(f):
    def neibu(*args,**kwargs):
        print('****')
        f(*args,**kwargs)
        print('*****')
    return neibu
@decor
def yanchanghui(*args,**kwargs):
    print(args)
    for x in args:
        print(x,end=' ')
    print()
    print(kwargs)
    for k,v in kwargs.items():
        print(k,v)
    print('演唱会')
yanchanghui('刘德华','张惠妹',age=18,address='广州')

带返回值的装饰器

def decor(f):
    def neibu(name,age):
        print('***')#1
        r=f(name,age)
        print('******')#4
        return r#5
    return neibu
@decor
def hanshu(name,age):
    print(name,age,'开演唱会')#2
    return name+str(age)#3
x=hanshu('刘德华',19)
print(x)

eg:

from functools import wraps
def decor(f):
    @wraps(f)
    def neibu(name,age):
        print('***')
        r=f(name,age)
        print('*****')
        return r
    return neibu
@decor
def hanshu(name,age):
    '''

    :param name:
    :param age:
    :return:
    '''
    print(name,age,'开演唱会')
    return name+str(age)
x=hanshu('刘德华',19)
print(x)
print(hanshu.__doc__)
print(hanshu.__name__)

eg:

def decor1(func):
    def neib(name,age):
        print('1')
        ret =func(name,age)
        print('2')
        return ret
    return neib
def decor2(func):
    def neib(name,age):
        print('1#')
        ret=func(name,age)
        print('2#')
        return ret
    return neib
@decor1
@decor2
def hello(name,age):
    print('hello')
    return name+str(age)
ret=hello('刘德华',19)
print(ret)

property方法

class Stu():
    def __init__(self,name,age):
        self.name=name
        self.__age=age
    @property
    def message(self):
        print('我在这儿')
        return self.__age
    @message.setter
    def message(self,x):
        print('11111')
        self.__age=x
s=Stu('张三',19)
s.message=29
print(s.message)
print(s.name)

作业
1.# 迭代器练习

class PrimeNumbers:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def isPrimeNum(self, k):
        if k < 2:
            return False
        for i in range(2, k):
            if k % i == 0:
                return False
        return True
    def __iter__(self):
        for k in range(self.start, self.end + 1):
            if self.isPrimeNum(k):
                yield k
for x in PrimeNumbers(1, 10):
    print(x)

2.# 生成器练习
生成器练习

def read_file(fpath):
    BLOCK_SIZE = 6
    with open(fpath, 'r') as f:
        while True:
            block = f.read(BLOCK_SIZE)
            if block:
                yield block
            else:
                return
import os
g = read_file(os.getcwd() + '\\aa.txt')
for content in g:
    print(content)

3.# 装饰器练习

from sys import stdout
def forever(fun):
    def inner():
        print("循环")
        while True:
            # nonlocal n
            n = input("请输入菱形上部的正三角的行数:")
            if n == "q" or n == "exit":
                print("程序已退出!")
                break
            fun(n)
    return inner
def verify_number(fun):
    def inner(n):
        print("验证输入的有效性")
        if isinstance(n, int) or n.isdigit():  # 判断字符串是否为纯整数字组成
            n = int(n)
            fun(n)
        else:
            print("请输入整数!!!")
    return inner
@forever
@verify_number
def print_diamond(n):
    for i in range(1, n + 1):
        for j in range(1, n - i + 1):
            stdout.write(' ')
        for k in range(1, 2 * i - 1 + 1):
            stdout.write('*')
        print()
    for i in range(1, n - 1 + 1):
        for j in range(1, i + 1):
            stdout.write(' ')
        for k in range(1, 2 * (n - i) - 1 + 1):
            stdout.write('*')
        print()
print_diamond()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值