#闭包函数,其中 exponent 称为自由变量
# def nth_power(exponent):
# def exponent_of(base):
# return base ** exponent
# return exponent_of # 返回值是 exponent_of 函数
# square = nth_power(2) # 计算一个数的平方
# cube = nth_power(3) # 计算一个数的立方
#
# print(square((square(2)))) # 计算 2 的平方
# print(cube(cube(2))) # 计算 2 的立方
# def nth_power(exponent):
# def exponent_of(base):
# return base ** exponent
# return exponent_of
# square = nth_power(2)
# #查看 __closure__ 的值
# print(square.__closure__)
# 装饰器
#funA 作为装饰器函数
# def funA(fn):
# print("C语言中文网")
# fn() # 执行传入的fn参数
# print("http://c.biancheng.net")
# return "装饰器函数的返回值"
#
# @funA
# def funB():
# print("学习 Python")
#
# 通过比对以上 2 段程序不难发现,使用函数装饰器 A() 去装饰另一个函数 B(),其底层执行了如下 2 步操作:
# 将 B 作为参数传给 A() 函数;
# 将 A() 函数执行完成的返回值反馈回 B。
# def funA(fn):
# # 定义一个嵌套函数
# def say(arc):
# print("Python教程:",arc)
# return say
#
# @funA
# def funB(arc):
# print("funB():", a)
# funB("http://c.biancheng.net/python")
def funA(fn):
# 定义一个嵌套函数
def say(*args,**kwargs):
fn(*args,**kwargs)
return say
@funA
def funB(arc):
print("C语言中文网:",arc)
@funA
def other_funB(name,arc):
print(name,arc)
funB("http://c.biancheng.net")
other_funB("Python教程:","http://c.biancheng.net/python")
Python @函数装饰器及用法(超级详细)
Python动态语言-动态添加属性和方法
import types
#定义了一个类
class Person(object):
def __init__(self, name = None, age = None):
self.name = name
self.age = age
def eat(self):
print("eat food")
#定义一个实例方法
def run(self, speed):
print("%s在移动, 速度是 %d km/h"%(self.name, speed))
#定义一个类方法
@classmethod
def testClass(self):
self.num = 100
print('nyou nn n nn 1')
#定义一个静态方法
@staticmethod
def testStatic():
print("---static method----")
#动态给对象添加方法
a=Person('网格',20)
a.run=types.MethodType(run,a)
a.run(180)
#动态给类添加方法(类方法和静态方法)静态方法
b=Person('静哥',25)
Person.meth=testStatic
b.meth()
#类方法
c=Person('进哥',22)
Person.test=testClass
print(c.test())
给Python的类和对象动态增加属性和方法 - phyger - 博客园