Lesson Twelve python basis - function of advanced features, worth a visit (white piao share)

# Write any number of acceptable parameters of function
# we want to write a function can accept any number of parameters

Solution #:
# To prepare a pharmaceutically function of any number of position parameters, may be used in the beginning of the parameter *
DEF AVG (First, REST *):
return ((First + SUM (REST)) / (. 1 + len ( rest)))

print(avg(1,2))#1.5
print(avg(1,2,3,4))#2.5

#rest is a tuple, which contains all the passed position parameter; calculating the following code will handle it as a sequence
# if you want to accept any number of keyword parameter may be used to begin with ** parameters:
Import HTML
DEF make_element (name, value, kwargs **):
key_values = [ '% S = "% S"'% for Item Item in kwargs.items ()]
kwarg_str = '' .join (key_values)
ELE = '<attrs {{name}}> {value} </ name} {>'. the format (name = name, attrs = kwarg_str, html.escape value = (value))
return ELE

str1 = make_element(‘item’,‘Albatatross’,size=‘large’,quantity=6)
print(str1)#Albatatross
str2 = make_element(‘p’,’’)
print(str2)#

<spam>

# Kwargs here is a dictionary, which contains all the key parameters (optional) pass over
# If you want the function to accept any number of colleagues positional parameters and keyword parameters, as long as the combined use * and ** can .

# In the function definition, with parameters starting with a position only as a last argument appears, and a parameter beginning with ** only appear as the last parameter.
# In
the back there are other parameters can still occur, this parameter is called keyword-only parameter

# Define functions with default parameters;
# we want to define a function with optional parameters is very simple - just copy the parameter definition, and to ensure that the default parameters can appear in the final.
# If the default value is variable container, then, for example, lists, sets or dictionaries, you should None as the default
# Note: The default parameters of the assignment, only binding once when the function definition! ! ! ! ; Followed default parameters assignment always immutable objects
# (such as None, True, False, strings, numbers)
# Do not write code in short:
DEF FUNC (A, lt = []):
Print (lt)
return lt
X FUNC = (. 1) # []
Print (X) # []
x.append (99)
x.append ( 'YOW! YOW! qeknow')
FUNC (2) # [99, 'YOW! yow! qeknow '] will eventually lead to default parameter value continues to be modified! ! !

a = …
print(a,type(a))#Ellipsis <class ‘ellipsis’>

# Carry additional state in the callback function
# We are writing the code needed to use the callback function, but hope the callback function can carry additional state for use in internal callback function

Solution #:
# Define the following function, will call a callback function:
# should all focus on the callback function of
DEF funcCallBack (FUNC, args, *, callback):
RES = FUNC (* args)
callback (RES )

def add(a,b):
return a+b

def my_print(res):
print(‘result={}’.format(res))

funcCallBack(add,(1,2),callback=my_print)#result=3

# A portable method for additional information in the callback method is to use binding (bound-method); instead of the normal function
# example below this example, each call, the number of prints callback function call:

class CallBackFuncClass():
def init(self):
self.count = 0
def handler(self,result):
self.count += 1
print(’[{}],result = {}’.format(self.count,result))
r = CallBackFuncClass()

for x in range(3):
funcCallBack(add,(2,3),callback=r.handler)
#[1],result = 5
#[2],result = 5
#[3],result = 5

# As an alternative class can use internal defined function to complete
DEF CallBackFuncClass ():
COUNT = 0
DEF Handler (Result):
nonlocal COUNT
COUNT + =. 1
Print ( "{}, Result = {}" the format (COUNT. , the Result))
return Handler

handler = CallBackFuncClass()

funcCallBack(add,(2,3),callback=handler)#1,result = 5
funcCallBack(add,(2,3),callback=CallBackFuncClass())#1,result = 5

# Last but not least important, additional parameters can also carry the state in the callback function, then the number of parameters to deal with the problem of partial ()

class Seq():
def init(self):
self.sequence = 0

def handler(res,seq:Seq):
seq.sequence += 1
print("{} res: {}".format(seq.sequence,res))

import functools as f
seq = Seq()
funcCallBack(add,(2,3),callback=f.partial(handler,seq = seq))#1 res: 5

# Access are defined in the interior of the closure variable
# we want to extend the closure by a function, such that the inner closure defined variables can be accessed and modified

Solution #:
# pay attention to the closure of the inner variables to the outside world completely isolated.
# Function and can be accessed by writing them as a function of attributes to provide access to the closure onto the inner support variable

def sample():
n = 0
def func():
print(‘n:’,n)
def get_n():
return n
def set_n(value):
nonlocal n
n = value

func.get_n = get_n
func.set_n = set_n
return  func

f = sample()
f()#n: 0
f.set_n(10)
f()#n: 10
print(f.get_n())#10

发布了17 篇原创文章 · 获赞 1 · 访问量 353

Guess you like

Origin blog.csdn.net/weixin_43520503/article/details/104557654