Python_ Decorator, Generator _ Dry Goods OH

Source: Internet
Author: User
Tags throw exception

Import time
Import Calendar
Import OS

# Time Format Familiar
"""
# Formatted as 2016-03-20 11:45:39 form
TIME01 = Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())
Print ()
# formatted as Sat 28 22:24:24 2016 form
Print (Time.strftime ("%a%b%d%h:%m:%s%Y", Time.localtime ()))
# Convert a format string to a timestamp
A = "Sat Mar 28 22:24:24 2016"
Print (Time.mktime (Time.strptime (A, "%a%b%d%h:%m:%s%Y")))

Print (Calendar.month (2017, 2))
Print (Calendar.calendar (2017, 1, 1, 3))

Print ("* * * *", Calendar.leapdays (2001, 2017))

#返回月份开始的前一天是周几及月份有几天
Print ("* * * *", Calendar.monthrange (2017, 7))
"""
# list Operations
"""
def change_mylist (tmplist):
Tmplist.append ([9, 9, 9])

Print (tmplist)

MyList = [1, 3, 4, 6]

Change_mylist (MyList)

Print (MyList)
"""
# String to Dictionary
"""
A = ' {' "name": "Lucy", "Age": Ten, "tmp": "Adssa"} '
Tmpdic = eval (a) #字符串转字典
For I, J in Tmpdic.items ():
Print ("39-%s-%s". Center (+, "*")% (I, J))

For I in Tmpdic:
Print ("42-{value}". Format (value = Tmpdic[i]). Center (20, "*"))
"""

"' Adorner
Principle: 1, can not modify the decorated source code 2, cannot modify the call mode of the decorated function
‘‘‘
# The parameter is not fixed
‘‘‘
def Tmp_timmer (func):
def tmp_warpper (*args, **kwargs):
Start_time = Time.time () # before function call
Print ("999". Center (20, "-"))
ret = func (*args, **kwargs) # function call
Stop_time = Time.time () # After a function call
Print ("* * * * * * * * * dif_time}". Format (Dif_time = (stop_time-start_time)))
return ret
Return Tmp_warpper

@tmp_timmer

Def time_test ():
Time.sleep (. 5)
Print ("Test---01")

Time_test ()
‘‘‘
# Functions with parameters to decorate
‘‘‘
def Tmp_zhuangshiqi (func):
def tmp_func (x, y):
Print ("Test---02")
RET = func (x, y)
Print ("666". Center (+, "*"), ret)
Return (RET-5)
Return Tmp_func

@tmp_zhuangshiqi
def time_test (x, y):
Print ("Test---01")
Time.sleep (2.3)
return (x + y)

Print ("3, 3"), Center (time_test, "-")
‘‘‘
# higher-order functions--function as variables
"' return value contains function name; pass one function as a parameter to another function '"
‘‘‘
def tmpfunc (x, y):
Print ("*******92*")
return x + y

def count_sum (x, func):
Print ("----96--", func)
return x * func

Print (Count_sum (4, Tmpfunc (1, 1)))
‘‘‘
# Adorner calls Beginner
‘‘‘
def wrapper_01 (func):
def test_func (*args, **kwargs):
Print ("* * *, before function call")
ret = func (*args, **kwargs)
Print ("* * * *, after function call * * * *", ret)
If RET is not None:
Return ret-3
Else
return ret

Return Test_func #返回 Test_func memory address

@wrapper_01 # using Adorners
Def test_print ():
Print ("* * * * * 116 * * * * *)
Time.sleep (2.5)
return 0

Print (Test_print ())

@wrapper_01
def test_print02 (x, y):
Print ("* * * * * 124 * * * * *)
Time.sleep (2.5)
return x + y

Print (test_print02 (3, 5))
‘‘‘
# Decorator Classic Case _ decorator pass parameter, function pass ...
"""
Username, password = "Allen", "123"

def auth (Checktype):
Print ("{Tmpcheck}". Format (Tmpcheck = checktype). Center (50, "-"))
def outer_wrapper (func):
def wrapper (*args, **kwargs):
NAME01 = input ("Input username:")
PASSWORD01 = input ("Input password:")
Print ("{check}". Format (check=checktype). Center (100, "*"))

if Checktype = = "A":
If name01 = = Username and password01 = = password:
ret = func (*args, **kwargs)
Print ("\033[31;1msuccess login!!!! \033[0m ")
return RET * 3
Else
Exit ("\033[33;1musername or password is wrong!\033[0m")
return 0
Else
If name01 = = Username and password01 = = password:
ret = func (*args, **kwargs)
Print ("\033[35;1msuccess login!!!! ---B \033[0m ")
return ret
Else
Exit ("\033[36;1musername or password is wrong! ----B \033[0m ")
return 0

Return wrapper

Return Outer_wrapper

@auth (Checktype = "A")
def home_page (x, y):
Print ("Login Page * * * * * *")
return x + y

@auth (Checktype = "B")
Def personal_page ():
Print ("View personal Information")


# function call
Print ("^^ ^^ ^^ ^^ ^^ ^", Home_Page (2, 3))
Personal_page ()
"""
# List Builder: two ways to build
"""
# Way One
#例一
Tmplist = [I * 2 for I in range (10)]
Print ("* * * * * * * * * 185", tmplist)

#例二
def del_int (x):
return x% 2

Print ("****** 196 * * * * * * * * * * *", [Del_int (i) for I in range (10)])

#方式二
A = []
For I in range (10):
A.append (2*i)

Print ("* * * * * * * * * * 191", a)
"""
# Fibonacci Numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34 ....
"""
# The value of the nth Fibonacci number
def fib (n):
If n < 2:
Return 1
Else
return fib (n-1) + fib (n-2)
# First n Fibonacci values and
def SUM_FIB (n):
sum_tmp = 0
For I in range (n):
Sum_tmp + = fib (i)
Return sum_tmp

input_int = Int (input ("input" number of Fibonacci Numbers: "))
Print (FIB (input_int))
Print (SUM_FIB (input_int))
"""
# generator Detailed: Yield keyword
"""
def fib (Tmp_max):
N, a, b = 0, 0, 1
While N < tmp_max:
Print ("**225**", b)
Yield B # Put the value of B in the fib.
A, B = B, A + b
n = n + 1
Return "program End" # exception message

f = fib (10)

# for I in F: # Loop output Generator generated content
# print ("231***", i)
# "After executing to this position, the change position is recorded, so the following loop does not execute"

While True:
Try
A = next (f)
Print ("* * * * * * 234", a)
Except Stopiteration as E:
Print ("Throw exception". Center ("*"), E.value)
Break
"""
# Generator: Parallel effect on single thread
"""
# yield is returned after saving the current state,
DEF consumer (name):
Print ("%s ready to eat buns!") "% (name))
While True:
Baozi = yield
Print ("Bun [%s] came, was [%s] ate!" "% (Baozi, name))

# Production of steamed buns
Def producer ():
C1 = Consumer ("A")
C2 = Consumer ("B")

C1.__next__ ()
C2.__next__ ()

Print ("Start making buns ....") ")
For I in range (10):
Time.sleep (1.0)
Print ("Make 2 buns!" ")
C1.send (i)
C2.send (i)
#调用函数
Producer ()
"""

Python_ Decorator, Generator _ Dry Goods OH

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.