- decorator
sometime we want to text a function ,but we need not to change this function ,we can use the decorator:
def outer2(fun):
def inner():
print("inner")
fun()
return inner
@outer2 #this means the function is "func = outer2(func)
def func():
print("this is first sentence")
func()
def use_logging(level):
def decorator(func):
def wrapper(*args, **kwargs):
if level == "warn":
logging.warn("%s is running" % func.__name__)
return func(*args)
return wrapper
return decorator
@use_logging(level='warn') #
means foo = use_logging(level = 'level') => foo = decorator(foo) => foo =wrapper() => warpper {return func()}
def foo(name="foo"):
print("this is %s " % name)
foo()
- partial function
it locks a function's parament ,so that make a defalut parament ,we need not to set it every time
import functools
int4 = int("123", base= 4)
print(int4)
def int2(str, base=2):
return int(str, base)
print(int2("1101"))
int3 = functools.partial(int,base = 3)
print(int3("22"))
def sum(a,b):
return a+b
sum_10 = functools.partial(sum, 10)#it means lock the "sum"function's first parament ,like sum(a = 10,b)
print(sum_10(5))
def sum_args(*args):
s = 0
for i in args:
s = s + i
return s
sum_args_10 = functools.partial(sum_args, 10)#it like sum_arge(10,*arges)
print(sum_args_10(1,2,3,4,5))
- list comprehensions
when we need to print this [i **2 for i in range (1,5)
[x**2 for x in range(1,5)]
and we can add other opertor to it :
[x**2 for x in range(1,11) if x % 2 == 0]
Permutations:
$
[m + n
for
m
in
'ABC'
for
n
in
'XYZ'
]
>>[
'AX'
,
'AY'
,
'AZ'
,
'BX'
,
'BY'
,
'BZ'
,
'CX'
,
'CY'
,
'CZ'
]
- generator
if we get a billon data ,but just a few to show for need ,we can use the generator .
the follwing is the generator :
from collections import Iterable
str ="qwer"
print(str.__dir__())#to show the more information ,if there show the func_name __iner__()
print(isinstance(str,Iterable))#it to jedge the object to can be iteration
i =str.__iter__()# give the object to i
for x in range (1,4):
print(i.__next__())#this is to move the cursor
4.2
yield
def a():
print('111')
#return 222
yield 2 #if return a generator ,it will show our a cursor to show,like the "return ",but it will not stop
print('niho')
yield 3
g = a()
r = g.__next__() #the same to
next(g)
r2 = g.__next__()
print(r)
print(r2)
it can developed to :
def func(n):
str = []
for i in range (0,n):
yield i
g = func(10000)
next(g)
next(g)