以下代码均采用Python 3.5.2 编写。新建一个名为HelloWorld.py的文件,当然名称无所谓,输入以下代码:
#func return
def line_conf():
b=15
def line(x):
return 2*x+b
b=5
return line
my_line=line_conf()
print(my_line(5))
#closure
print(my_line.__closure__)
print(my_line.__closure__[0].cell_contents)
def line_conf2(a,b):
def line(x):
return a*x+b
return line
line1=line_conf2(1,1)
line2=line_conf2(4,5)
print(line1(1))
print(line2(1))
#decorator
def decorator_demo(old_function):
def new_function(a,b):
print("input", a, b)
return old_function(a,b)
return new_function
@decorator_demo
def square_sum(a,b):
return a**2+b**2
@decorator_demo
def cubic_sum(a,b):
return a**3+b**3
print(square_sum(2,1))
print(cubic_sum(2,1))
def pre_str(pre=""):
def decorator(old_function):
def new_function(a,b):
print(pre+" input ",a, b)
return old_function(a,b)
return new_function
return decorator
@pre_str("^_^")
def square_diff(a,b):
return a**2-b**2
print(square_diff(2,1))
def decorator_class(SomeClass):
class NewClass(object):
def __init__(self, age):
self.total_display=0
self.wrapped=SomeClass(age)
def display(self):
self.total_display+=1
print("total display", self.total_display)
self.wrapped.display()
return NewClass
@decorator_class
class Bird(object):
def __init__(self, age):
self.age=age
def display(self):
print("My age is ",self.age)
eagle_lord=Bird(5)
for i in range(3):
eagle_lord.display()
#lambda
lambda_sum = lambda x,y: x+y
print(lambda_sum(1,2))
#map
data_list=[1,3,5,6]
result=map(lambda x: x+3, data_list)
for i in result:
print(i)
data_list1=[1,3,5,7]
data_list2=[2,4,6,8]
result=map(square_sum,data_list1,data_list2)
for i in result:
print(i)
读懂以上代码即可轻松掌握装饰器、map函数等基本命令使用方法,方便起见,可以考虑将尚未读到的代码注释掉,一段段阅读。
时间: 2024-10-30 07:50:33