python-装饰器 闭包函数
装饰器 闭包函数
闭包函数:变量 函数销毁之后,有时候需要这个函数的变量 闭包解决这个问题
形成条件
1.实现函数嵌套
2.内部函数使用外部函数的变量
3.外部函数返回内部函数
简单的闭包
# 外部函数 def test1(): b=10 # 内部函数 def test2(): print(b) return test2 a=test1() print(a())
执行结果
10
None
拿到函数的变量,在另外一个函数计算
def test1(num1): def test2(num2): result=num1+num2 print(result) return test2 test2=test1(2) test2(3)
执行结果:
5
装饰器 @方法名
给已有的函数增加额外的功能
发表的功能:先登录,检查登录,登录。只有登登录完成之后才能去发表评论
# 检查有没有登录 def check(fc): print('检查登录') def inner(): print('登录') fc() return inner # 发表评论 def comment(): print('发表评论') c=check(comment) c()
执行结果:
检查登录
登录
发表评论
# @方法名 def check(fc): print('检查登录') def inner(): print('登录') fc() return inner # 发表评论 # @check 相当于check(comment) 代理的意思 @check def comment(): print('发表评论')
comment() # comment()相当于inner()
执行结果:
检查登录
登录
发表评论
类方法和静态方法实例方法
class Foo(object): def instance_method(self): print('实例方法') @staticmethod def static_method(): print('静态方法') @classmethod def class_method(cls): print('类方法') # 调用方法 怎么调用?实例方法就说对象方法 foo=Foo() foo.instance_method() foo.class_method() foo.static_method() # 静态方法和类方法还有实例方法都可以通过对象取调用 # 类去调用 Foo.static_method() Foo.class_method() Foo.instance_method(self='11') #静态方法和类方法都是可以通过类调用
执行结果:
实例方法
类方法
静态方法
静态方法
类方法
实例方法
静态方法:静态方法中没有和类相关的东西
独立的空间 公共的区域 都可以用
import time class TimeTest(object): def __init__(self,hour,minute,second): self.hour=hour self.minute=minute self.second=second @staticmethod def showTime(): return time.strftime('%H:%M:%S',time.localtime()) print(TimeTest.showTime())
执行结果:
11:53:03
类方法
class Tool: count=0 def __init__(self,name): self.name=name Tool.count+=1 @classmethod def show_tool_count(cls): print('工具对象的总数%d'%cls.count) tool1=Tool('簇头') tool2=Tool('斧头') tool3=Tool('棒槌') Tool.show_tool_count()
执行结果:
工具对象的总数3