My way to self-study Python (Phase 2 Day8)

1. Some Usages of Decorators and Functions

from functools import wraps
def wrapper(func):
    @wraps(func)
    def inner():
        func()
    return inner
@wrapper
def func1():
    '''jisfhsdkfkd'''
    print('ddf')
print(func1.__name__)
func1()
print(func1.__doc__)

# def index():
#     '''This is a homepage information.'''
#     print('from index')
#
# print(index.__doc__)    #Ways to view function annotations
# print(index.__name__)   #How to view function names

2. Decorator tape parameters

FLAG = True
def out(flag):
    def wrapper(func):

        def inner():
            if flag:
                print(123)
                func()
            else:
                func()
        return inner
    return wrapper
@out(FLAG)
def func1():
    '''jisfhsdkfkd'''
    print('ddf')
func1()

3. Multilayer Decorators

def wrapper1(func):
    def inner1():
        print('wrapper1 ,before func')
        ret = func()
        print('wrapper1 ,after func')
        return ret
    return inner1

def wrapper2(func):
    def inner2():
        print('wrapper2 ,before func')
        ret = func()
        print('wrapper2 ,after func')
        return ret
    return inner2

def wrapper3(func):
    def inner3():
        print('wrapper3 ,before func')
        ret = func()
        print('wrapper3 ,after func')
        return ret
    return inner3

@wrapper3
@wrapper2
@wrapper1
def f():
    print('in f')
    return 'Ha ha ha'

print(f())

//results of enforcement
wrapper3 ,before func
wrapper2 ,before func
wrapper1 ,before func
in f
wrapper1 ,after func
wrapper2 ,after func
wrapper3 ,after func
//Ha ha ha

4. Brush 2 Questions

# 1.Write a decorator to add authentication functions to multiple functions (user's account password comes from files).
# Require successful login once, follow-up functions do not need to re-enter user name and password
# FLAG = False
# def login(func):
#     def inner(*args,**kwargs):
#         global FLAG
#         '''Login procedure'''
#         if FLAG:
#             ret = func(*args, **kwargs)
#             return ret
#         else:
#             username = input('username:')
#             password = input('password:')
#             if username == 'boss_gold' and password == '22222':
#                 FLAG = True
#                 ret = func(*args,**kwargs)
#                 return ret
#             else:
#                 print('Login failed')
#     return inner
# @login
# def shop_add():
#     print('Add an item')
# @login
# def shop_del():
#     print('Delete an item')
# shop_add()
# shop_del()


# 2.Write a decorator to add a record call function to multiple functions, requiring each call function to write the name of the called function to the file.
def log(func):
    def inner(*args,**kwargs):
        with open('log','a',encoding = 'utf-8') as f:
            f.write(func.__name__ + '\n')
        ret = func(*args,**kwargs)
        return ret
    return inner
@log
def shop_add():
    print('Add an item')
@log
def shop_del():
    print('Delete an item')
shop_add()
shop_del()
# 1.Write a function to download the content of a web page. The function required is: the user passes in a url,Function returns the result of the download page
# 2.Write a decorator for Title 1 to realize the function of caching web content:
# Specific: The downloaded pages are stored in the file. If there is value in the file (file size is not 0), the content of the page will be read from the file first. Otherwise, the downloaded pages will be downloaded and stored in the file.
import os
from urllib.request import urlopen
def cache(func):
    def inner(*args,**kwargs):
        if os.path.getsize('web_cache'):
            with open('web_cache','rb') as f:
                return f.read()
        ret = func(*args,**kwargs)
        with open('web_cache','wb') as f:
            f.write(b'***'+ret)
        return ret
    return inner

@cache
def get(url):
    code = urlopen(url).read()
    return code

ret = get('http://www.baidu.com')
print(ret)

ret = get('http://www.baidu.com')
print(ret)

5. Several Methods of Valuing from Generator

    # next
# for
# Mandatory Conversion of Data Types: Occupying Memory
def generator():
    for i in range(20):
        yield 'WOW!%s'%i

g = generator()  #Call the generator function to get a generator
print(list(g))# Mandatory conversion of data types : Occupied memory
# ret = g.__next__()     #Each execution g.__next__That is to take the value from the generator, which indicates that the code in the generator function will continue to execute.
# print(ret)
# num = 0
# for i in g:
#     num += 1
#     if num > 5:
#         break
#     print(i)

6. Generator Function Advancement

# send gets the next value in almost the same way as next
# Just pass a data to the location of the previous yield when you get the next value
# Notes for using send
# The first time you use a generator, you use next to get the next value
# The last yield cannot accept external values
def generator():
    print(123)
    content = yield 1
    print(content)
    print(456)
    yield 2
    print(789)

g = generator()
print(g.__next__())
print(g.send('hello'))
print(g.send('hello'))

7. Calculate moving average

def average():
   sum = 0
   count = 0
   avg = 0
   while 1:
       num = yield avg
       sum = sum + num
       count += 1
       avg = sum/count

avg_g = average()
avg_g.__next__()
avg1 = avg_g.send(10)
# avg1 = avg_g.send(50)


print(avg1)

Calculating Moving Average--Decorator of Preexcitation Coefficient

#The purpose of this decorator is to activate the program ahead of time. g.__next__()
#No need to execute when it's convenient for customers to calculate g.__next__()
# def init(func):   #Decorator
#     def inner(*args,**kwargs):
#         g = func(*args,**kwargs)    #g = average()
#         g.__next__()
#         return g
#     return inner
#
# @init
# def average():
#     sum = 0
#     count = 0
#     avg = 0
#     while True:
#         num = yield avg
#         sum += num    # 10
#         count += 1    # 1
#         avg = sum/count
#
# avg_g = average()   #===> inner
# ret = avg_g.send(10)
# print(ret)
# ret = avg_g.send(20)
# print(ret)

8.yield from

def generator():
    a = 'adfgg'
    b = 'dskdl'
    for i in a:#Two sentences correspond to==>yield from a
        yield i#Two sentences correspond to==>yield from a
    for i in b:
        yield i
g = generator()
for i in g:
    print(i)

9. List Derivatives and Generator Expressions

Conclusion:

1. The generator expression is obtained by replacing () with [] of list parsing.

2. List parsing and generator expressions are both convenient programming methods, but generator expressions save more memory.

3.Python not only uses the iterator protocol, but also makes for loops more general. Most built-in functions also use iterator protocols to access objects. For example, the sum function is Python's built-in function, which uses the iterator protocol to access objects, while the generator implements the iterator protocol, so we can directly calculate the sum of a series of values in this way:

# egg_list = ['Egg%s' %i for i in range(10)]#List parsing
# print(egg_list)
# egg_tur = ('Egg%s' %i for i in range(10))#Generator Expressions
# print(egg_tur)
# print(egg_tur.__next__())
# print(next(egg_tur)) #next The essence is to call__next__
# print(egg_tur.__next__())


t = sum(x ** 2 for x in range(4))
print(t)
s = sum([x ** 2 for x in range(4)])
print(s)
m = sum((0,1,4,9))
print(m)
print(sum((1,2)))
#[Each element or operation associated with the element for element in Iterable data types]    #Processing one by one after traversing
#[Conditional element-related operations for element in Iterable data types if Element-related conditions]   #Screening function

# #30 All numbers within 3 divisible
# print([i for i in range(30) if i%3 == 0])
# print((i for i in range(30) if i%3 == 0))
# # Example three:Find a nested list with two names'e'All names
# names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
#          ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
# ret = [name for lst in names for name in lst if name.count('e') ==2]
# # ret = (name for lst in names for name in lst if name.count('e') ==2)
# print(ret)
#

#Dictionary Derivation


# Example 1: Put a dictionary's key and value Swap
# dic = {'a':10,'b':20}
# dic_reverse = {dic[k]:k for k in dic}
# print(dic_reverse)
#

# Example 2: Combining case-sensitive value Value will be k Unify into lowercase
# d = {'s':10}
# print(d.get('b',0))
# print(d.get('s'))

# mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
# s = {k.lower():mcase.get(k.lower(),0) + mcase.get(k.upper(),0) for k in mcase}
# print(s)

#Set Derivation, with Result Removal Function

# s = {x**2 for x in [1,2,-1]}
# print(s)
# squared = {x**2 for x in [1, -1, 2]}
# print(squared)


#Various Derivatives: Generator List Dictionary Set
    #Ergodic operation
    #Screening operation

Generator:

Essence: Iterator, so it has _iter_ method and _next_ method

Features: Lazy Operations, Developer Customization

Advantages of using generators:

1. Delay calculation and return one result at a time. That is to say, it will not generate all the results at once, which will be very useful for large data processing.

2. Improving code readability

print(sum([i for i in range(100)]))#Large memory footprint,Machines can easily get stuck.
print(sum(i for i in range(100000)))#Almost no memory
print(i for i in range(100))#Almost no memory

11. brush problem

# 3.Processing files, users specify the files and contents to be searched, and output each line of the file containing the contents to the screen

# def func(filename,s):
#     with open(filename,encoding = 'utf-8') as f1:
#         for i in f1:
#             if s in i:
#                 yield i
#
# g = func('ss','generator')
# for i in g:
#     print(i.strip())

# def check_file(filename,aim):
#     with open(filename,encoding='utf-8') as f:   #handle : handler,File operator, file handle
#         for i in f:
#             if aim in i:
#                 yield i
#
# g = check_file('1.Review.py','generator')
# for i in g:
#     print(i.strip())

# 4.Write a generator that reads content from a file and adds it before each read'***'It is then returned to the user.
# def check_file(filename):
#     with open(filename,encoding='utf-8') as f:   #handle : handler,File operator, file handle
#         for i in f:
#             yield '***'+i
#
# for i in check_file('1.Review.py'):
#     print(i.strip())
def func(filename):
    with open(filename,encoding = 'utf-8') as f1:
        for i in f1:
            yield '***'+i


g = func('ss')
for i in g:
    print(i.strip())

12. Generator expression interview questions

# def demo():
#     for i in range(4):
#         yield i
#
# g=demo()
#
# g1=(i for i in g)
# g2=(i for i in g1)
#
# print(list(g))
# print(list(g1))
# print(list(g2))

def add(n,i):
    return n+i

def test():
    for i in range(4):
        yield i

g=test()
# for n in [1,10,5]:
#     g=(add(n,i) for i in g)
n = 1
g=(add(n,i) for i in test())
n = 10
g=(add(n,i) for i in (add(n,i) for i in test()))
n = 5
g=(15,16,17,18)


print(list(g))

13. Built-in functions

Scope correlation

Acquiring Local and Global Variables Based on Dictionary Form

globals() - A dictionary for global variables

locals() - Gets a dictionary of local variables in the namespace in which this method is executed

# print()
# input()
# len()
# type()
# open()
# tuple()
# list()
# int()
# bool()
# set()
# dir()
# id()
# str()


# print(locals())  #Returns all names in local scope
# print(globals()) #Returns all names in global scope
# global variable
# nonlocal variable

#iterator.__next__()
# next(iterator)
# iterator = iter(Iterable)
# iterator = Iterable.__iter__()

# range(10)
# range(1,11)
# print('__next__' in dir(range(1,11,2)))

# dir Ways to view the ownership of a variable
# print(dir([]))
# print(dir(1))

# help
# help(str)

# variable
# print(callable(print))
# a = 1
# print(callable(a))
# print(callable(globals))
# def func():pass
# print(callable(func))

import time
# t = __import__('time')
# print(t.time())

# If a method belongs to a variable of a data type, it uses.call
# If a method does not depend on any data type, it calls directly -- built-in functions and custom functions

# f = open('1.Review.py')
# print(f.writable())
# print(f.readable())

#id
#hash - For the same hash Data hash Values are invariable during the execution of a program
#     - Addressing Method of Dictionary
# print(hash(12345))
# print(hash('hsgda I don't want you to go. nklgkds'))
# print(hash(('1','aaa')))
# print(hash([]))

# ret = input('Tips: ')
# print(ret)

# print('Our motherland is a garden',end='')  #End character of specified output
# print('Our motherland is a garden',end='')
# print(1,2,3,4,5,sep='|') #Specifies the delimiter between output values
# f = open('file','w')
# print('aaaa',file=f)
# f.close()

# import time
# for i in range(0,101,2):
#      time.sleep(0.1)
#      char_num = i//2
#      per_str = '\r%s%% : %s\n' % (i, '*' * char_num) \
#          if i == 100 else '\r%s%% : %s' % (i,'*'*char_num)
#      print(per_str,end='', flush=True)

14. progress bar

#Progress note
import time
for i in range(0,101,2):
     time.sleep(0.1)
     char_num = i//2
     per_str = '\r%s%% : %s\n' % (i, '*' * char_num) \
         if i == 100 else '\r%s%% : %s' % (i,'*'*char_num)
     print(per_str,end='', flush=True)

Keywords: Python encoding Programming

Added by euph on Fri, 17 May 2019 02:25:58 +0300