Python path _ function instance and decorator Introduction

Source: Internet
Author: User

First, the exercise explanation

1, write function, return a list of cards, there are 52 items, each item is a tuple. For example: [(' Hearts ', 2), (' Grass flower ', 2), ... (' Spades, ' A ')

DefCards (): num=[]For VIn range (2,11): Num.append (v) num.extend ([‘J‘,‘Q‘,‘K‘,‘A‘) type=[ '  Hearts ",  '  grass flower  '  block  '  spades  "[] for i in num: for J in Type:result.append ((j,i)) return Resultprint (Cards ())           

2, write function, pass n number, return dictionary: {' max ': Max, ' min ': minimum}. For example: Min_max (2, 5, 7, 8, 4), return: {' Max ': 8, ' min ': 2}

 def max_min (*args): The_max=args[0] the_min=args[0] for i in args: if i> The_max:the_max=i if i< the_min:the_min=i return { ' max ": The_max, ' min " :the_min} print (Max_min (2,4,1,55,-3))          

3, write function, specifically calculate the area of the graph. Where nesting functions, calculating the area of a circle, the area of a square, and the area of a rectangle

   Call the function area (' Circle ', circle radius)  to return the areas of the circle
Call function area (' Square ', edge length) returns the square
Call function area (' Rectangle ', long, wide) returns the square of the rectangle
#方法一:
ImportMathdef area (name,*args):DefAreas_rectangle (x, y):Return x*YDefArea_square (x):Return x**2DefArea_round (R):Return math.pi*r*RIf name=="Circular":Return Area_round (*ArgsElif name=="Square":return area_square (*args) elif name== " rectangle ": return areas_rectangle (*args) print (area ( " rectangle ", 3, 4print (area ( " round ", 3print (area ( ' square
#Method Two (eval)ImportMathdef area (Name,*args): def  rectangle (x, y): return x* Y def square (x): return x** 2 def round (R): return Math.pi*r*r if name in< Span style= "COLOR: #000000" > locals (): return eval (name) (* args) print (area ( "rectangle< Span style= "COLOR: #800000", "13,2)"           
4, write the function, pass in a parameter n, return the factorial of N. Example: Cal (7) Calculates 7 * 6 * 5 * 4 * 3 * 2 * 1
EF cal (n):    result=1 in    range (n,0,-1):        result=result*i    return result Print (CAL (7))     

5. Fibonacci sequence: [1,1,2,3,5,8,13,...], each element is the sum of the first two elements

(1) When the required length is less than a certain value:

L = [All] whilelen (l) <20:    l.append (l[-1]+l[-2])print (l)    

(2) When the requirement is less than a certain number:

L = [All] whilel[-1]<4000000:    l.append (l[-1]+l[-2])del l[-1]print (l)  

Second, function decorator

function expansion of the original function without modifying the contents of the original function and calling mode

1. Calculating function Execution Time instance

ImportTimedef Timmer (func):#装饰器def innner (*args,**kwargs): start= time.time () Ret=func (*args,**kwargs) End=time.time () print (Start-end) return ret return Innner@timmer  #语法糖, equivalent Name=timmer (name) def name (A, b):  #被装饰函数 print ( Span style= "COLOR: #800000" > '  Viva boss  " ) return a+b 

Name (4,6)

2. Print an instance of the function name that is currently being called

DefWrapper (func):def inner (*args,**Kwargs):Print‘The function you are currently calling is:%s'%func.__name__) Ret=func (*args,**kwargs) return ret return Inner@wrapperdef Welcome (name): print ( ' welcome,%s '%name) Welcome ( ' zhangli ' ) @wrapper def home (): print ( '  Welcome to home page ) Home ()            

Job Title:

1, write the adorner, for a number of functions and authentication function (the user's account password from the file), required to log on successfully once, the subsequent functions do not need to enter the user name and password
flag=FalseDefLogin (func):def inner (*args,**Kwargs):GlobalFlagWhileNotFlag:name=input (‘Please enter user name:‘) Pwd=input (‘Please enter your password:‘) with open (‘File‘,‘R', encoding=‘Utf-8‘) as F:For lineInchF:lst=line.strip (). Split (‘|‘)If NAME==LST[0]and pwd==lst[1]: print ( " landed successfully") Flag=true whlie flag:ret=func (*args,** kwargs) return ret return Inner@logindef name1 (): print ( " How are you?  ") @login def name2 (): print ("  I'm okay ') name1 () name2 ()        
Original: https://www.cnblogs.com/seven-007/p/7460241.html

Python path _ function instance and decorator Introduction

Related Article

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.