1、装饰器执行流程

装饰器可用于权限管理;

装饰器:将原函数替换为wrapper函数

def outer()
@outer  --- func1作为参数传入outer()
def wrapper()  --- wrapper()放入内存
return wrapper   --- 返回wrapper地址,Func1重新赋值为wrapper
Func1()  --- 调用func1函数
def wrapper()
print '验证'
def Func1()
print 'func1'
[root@localhost decorate]# python main.py
验证
func1
验证
func2
[root@localhost decorate]# cat main.py
#!/usr/bin/python27
#coding:utf-8def outer(fun):def wrapper():print '验证'fun()return wrapper@outer
def Func1():print 'func1'@outer
def Func2():print 'func2''''
Func1=
def wrapper():print '验证'fun()
'''Func1()
Func2()
[root@localhost decorate]#

带参数的装饰器

[root@localhost decorate]# python27 main1.py
验证
func1 alex
[root@localhost decorate]# cat main1.py
#!/usr/bin/python27
#coding:utf-8def outer(fun):def wrapper(arg):print '验证'fun(arg)return wrapper@outer
def Func1(arg):print 'func1',arg'''
Func1=
def wrapper(arg):print '验证'fun(arg)
'''Func1('alex')
[root@localhost decorate]#

在函数执行的前后,执行任意函数

def Filter(before_func,after_func): def outer(main_func):def wrapper(request,kargs): before_result = before_func(request,kargs)if(before_result != None): return before_result;main_result = main_func(request,kargs)if(main_result != None):return main_result;after_result = after_func(request,kargs)if(after_result != None):return after_result;return wrapperreturn outer @Filter(AccountFilter.Before, AccountFilter.After) def List(request,kargs):pass

2、类与对象

封装性:将name,age属性封装到self中

内存图

类的内存:                               对象的内存

|                                                 |

静态字段                            动态字段:self.name

动态方法、静态方法   --->引用      方法

[root@localhost ~]# python27 index.py
cxiong 29
xmzhang 28
中国
[root@localhost ~]# cat index.py
#!/usr/bin/python27
#coding:utf-8

class Person():
    nation='中国'    --- 静态字段:nation只属于class,静态字段只有一份,对象内存中不存在;
    def __init__(self,name,age):
        self.name=name  --- 动态字段:self.name属于对象
        self.age=age    ---
动态字段:self.age属于对象

p1=Person('cxiong',29)
p2=Person('xmzhang',28)
print p1.name,p1.age
print p2.name,p2.age
print p1.nation
[root@localhost ~]#

注意:类不能访问动态字段;对象可以访问静态字段

静态字段、动态字段、静态方法、动态方法和装饰器

作用:提供统一的方法和数据,用于处理类的请求

[root@localhost ~]# cat index.py
#!/usr/bin/python27
#coding:utf-8class Person():#静态字段nation='中国'def __init__(self,name,age):#动态字段self.name=nameself.age=age#动态方法    def Eat(self):print self.name+' eating...'#静态方法  --- 不需要实例化类,即可调用方法@staticmethoddef Breath():print 'breathing...'#装饰器 --- 将方法访问形式作为字段形式访问@propertydef Sing(self):print self.name+' singing...'p1=Person('cxiong',29)
p2=Person('xmzhang',28)print p1.name,p1.age
print p2.name,p2.age
print p1.nation
p1.Eat()
p2.Eat()
Person.Breath()
p1.Sing

__dict__与dir()的区别

print m1.__dict__   ---类所有字段
{'_Person__gender': 'male', 'age': 29, '_man__gender': 'male', 'name': 'cxiong'}print dir(m1)   --- 类所有的方法及字段
['Breath', 'Eat', 'ShowGender', 'Sing', '_Person__gender', '__call__', '__class__', '__del__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_man__gender', 'age', 'name', 'nation', 'work']

3、面向对象与函数式编程的区别

静态方法与模块形式的区别:内存上没区别,区别在于,静态方法逻辑上属于类;

静态方法是面向对象语言解决对象重复构造方法时产生的,python模块化语言也可以解决;

多态:将相似的方法包装在同一个模块中;

python支持模块化编程,也支持反射;等同于面向对象编程java、.net

面向对象:可以创建模板

4、私有字段和私有方法

作用:安全

[root@localhost ~]# python index1.py
male
[root@localhost ~]# cat index1.py
#!/usr/bin/python27
#coding:utf-8class Person():#静态字段nation='中国'def __init__(self,name,age,gender):#动态字段self.name=nameself.age=age#私有字段self.__gender=gender#动态方法    def Eat(self):print self.name+' eating...'#静态方法@staticmethoddef Breath():print 'breathing...'#装饰器 @propertydef Sing(self):print self.name+' singing...'@property --- 私有字段不能被外部访问,但是可以使用方法访问def ShowGender(self):return self.__genderp1=Person('cxiong',29,'male')
p2=Person('xmzhang',28,'female')
print p1.ShowGender

只读私有字段和可改写私有字段

[root@localhost ~]# cat index1.py
#!/usr/bin/python27
#coding:utf-8class Person():   --- 没有继承object是可读可写;继承了object一个是可读,一个是可写#静态字段nation='中国'def __init__(self,name,age,gender):   --- 构造函数#动态字段self.name=nameself.age=age#私有字段self.__gender=gender#动态方法    def Eat(self):print self.name+' eating...'#静态方法@staticmethoddef Breath():print 'breathing...'#装饰器 @propertydef Sing(self):print self.name+' singing...'#只读私有字段@propertydef ShowGender(self):return self.__gender#可改私有字段@ShowGender.setterdef ShowGender(self,value):self.__gender=valuep1=Person('cxiong',29,'male')
p2=Person('xmzhang',28,'female')
print p1.ShowGender
p1.ShowGender='female'
print p1.ShowGender

5、析构函数及__call__方法

[root@localhost ~]# python index1.py
male
female
解释器要销毁person了...
解释器要销毁person了...
[root@localhost ~]# cat index1.py
#!/usr/bin/python27
#coding:utf-8class Person(object):#静态字段nation='中国'#构造函数def __init__(self,name,age,gender):#动态字段self.name=nameself.age=age#私有字段self.__gender=gender#析构函数,用于销毁对象时使用;一般不使用,常用于操作文件def __del__(self):print '解释器要销毁person了...'def __call__(self):print 'call'#动态方法    def Eat(self):print self.name+' eating...'#静态方法@staticmethoddef Breath():print 'breathing...'#装饰器 @propertydef Sing(self):print self.name+' singing...'#只读私有字段,property常用于私有字段@propertydef ShowGender(self):return self.__gender#可改私有字段@ShowGender.setterdef ShowGender(self,value):self.__gender=valuep1=Person('cxiong',29,'male')
p2=Person('xmzhang',28,'female')
print p1.ShowGender
p1.ShowGender='female'
print p1.ShowGender
p1()  #执行__call__方法[root@localhost ~]# python index1.py
male
female
call
解释器要销毁person了...
解释器要销毁person了...

6、继承

[root@localhost ~]# python index1.py
work hard...
cxiong singing...
breathing...
解释器要销毁person了...
[root@localhost ~]# cat index1.py
#!/usr/bin/python27
#coding:utf-8class Person(object):#静态字段nation='中国'#构造函数def __init__(self,name,age,gender):#动态字段self.name=nameself.age=age#私有字段self.__gender=gender#析构函数def __del__(self):print '解释器要销毁person了...'#动态方法    def Eat(self):print self.name+' eating...'#def __call__(self):print 'call'#静态方法@staticmethoddef Breath():print 'breathing...'#装饰器 @propertydef Sing(self):print self.name+' singing...'#只读私有字段@propertydef ShowGender(self):return self.__gender#可改私有字段@ShowGender.setterdef ShowGender(self,value):self.__gender=value#man继承Person类,私有方法__gender无法继承
class man(Person):#重写__init__方法def __init__(self):self.name='cxiong'self.__gender='male'#新增work方法def work(self):print 'work hard...'m1=man()
m1.work()
m1.Sing
m1.Breath()

7、新式类与经典类的区别

新式类:继承object,字段为只读和可写两种;

经典类:不继承object,字段均为读写

使用新式类的原因:经典类存在多继承bug,深度优先,而非广度优先,请参考以下内容

https://docs.python.org/release/2.2.3/whatsnew/sect-rellinks.html

[root@localhost ~]# cat index1.py
#!/usr/bin/python27
#coding:utf-8class Person(object):#静态字段,Person.nation获取nation='中国'#构造函数def __init__(self,name,age,gender):#动态字段self.name=nameself.age=age#私有字段self.__gender=genderprint 'person init...'#析构函数def __del__(self):print '解释器要销毁person了...'#动态方法    def Eat(self):print self.name+' eating...'#def __call__(self):print 'call'#静态方法@staticmethoddef Breath():print 'breathing...'#装饰器 @propertydef Sing(self):print self.name+' singing...'#只读私有字段@propertydef ShowGender(self):return self.__gender#可改私有字段@ShowGender.setterdef ShowGender(self,value):self.__gender=value#man继承Person类
class man(Person):#重写__init__方法def __init__(self):self.name='cxiong'self.__gender='male'print 'man init...'#调用父类的init方法1Person.__init__(self,'cxiong',29,'male')#调用父类的init方法2super(man,self).__init__('cxiong',29,'male')#新增work方法def work(self):print 'work hard...'m1=man()
m1.work()
m1.Sing
m1.Breath()[root@localhost ~]# python index1.py
man init...
person init...
person init...
work hard...
cxiong singing...
breathing...
解释器要销毁person了...
[root@localhost ~]#

8、多继承

python特有的特性

[root@localhost ~]# python multiple.py
this is D
save method from --A--
[root@localhost ~]# cat multiple.py
#!/usr/bin/python27
#coding:utf-8class A:def __init__(self):print 'this is A'def save(self):print 'save method from --A--'class B(A):def __init__(self):print 'this is B'class C(A):def __init__(self):print 'this is C'def save(self):print 'save method from --C--'class D(B,C):def __init__(self):print 'this is D'c=D()
c.save()
[root@localhost ~]# vim multiple.py
[root@localhost ~]# python multiple.py
this is D
save method from --C--
[root@localhost ~]# cat multiple.py
#!/usr/bin/python27
#coding:utf-8class A(object):def __init__(self):print 'this is A'def save(self):print 'save method from --A--'class B(A):def __init__(self):print 'this is B'class C(A):def __init__(self):print 'this is C'def save(self):print 'save method from --C--'class D(B,C):def __init__(self):print 'this is D'c=D()
c.save()
[root@localhost ~]#

9、接口

规范:抽象类+抽象方法=接口

from abc import ABCMeta, abstractmethod
class Bar:__metaclass__ = ABCMeta  @abstractmethod    def Fun(self):passclass Foo(Bar):    def __init__(self):print '__init__'Foo()

转载于:https://blog.51cto.com/f1yinsky/1922991

python-装饰器,类与对象,私有字段,析构,__call__,继承,多继承,接口相关推荐

  1. python装饰器类-基于类的python装饰器

    python装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象.在Python中一般callable对象都是函数,但也有例外.只要某个对象重 ...

  2. python装饰器类-PYTHON里的装饰器能装饰类吗

    扩展回答 如何理解python里的装饰器 通常可以理解它是一个hook 的回调函数. 或者是理解成python 留给二次开发的一个内置API. 一般是用回调和hook 方式实现的. 如何理解Pytho ...

  3. python装饰器类-Python 装饰器装饰类中的方法

    title: Python 装饰器装饰类中的方法 comments: true date: 2017-04-17 20:44:31 tags: ['Python', 'Decorate'] categ ...

  4. 50 Python - 装饰器 类定义装饰器

    04 类定义装饰器 上节通过函数定义装饰器,本节通过类定义装饰器 001 定义类装饰器 定义一个类,类里面两个函数,一个构造函数init(),一个调用函数call() 构造函数init时候,传递一个函 ...

  5. python装饰器类-Python 装饰器、类装饰器、属性装饰器

    今天来介绍一下python的装饰器. 1.首先来介绍一下简单的装饰器, def play(): return "i can play" if __name__ == '__main ...

  6. python装饰器类-python_类装饰器

    一.定义 装饰器就是一个给对象添加额外功能的函数,其本质是函数.它的基本构造:高阶函数+函数嵌套+闭包.基础知识讲解详见:https://blog.51cto.com/10836356/2095118 ...

  7. python装饰器类-Python类装饰器

    上次介绍了Python的函数装饰器,这次我们来讲一讲Python的类装饰器. Python的类装饰器基本语法如下: defdecorator(cls):print "6666666" ...

  8. python装饰器类-python装饰器2:类装饰器

    本文是装饰器相关内容的第二篇,关于类装饰器. "类装饰器"有两种解读方式:用来装饰类的装饰器:类作为装饰器装饰其它东西.你如何认为取决于你,两种说法都有出现在其它的文章中.我的文章 ...

  9. python装饰器类-Python装饰器15-开始使用类作为装饰器

    基于前面的使用函数作为装饰器的理解,将类作为装饰器时需要保证以下几点 类的实例是可调用的 类需要一个地方讲被装饰的函数传入到类的实例里 第一条可以通过__call__实现,第二条可以通过__init_ ...

最新文章

  1. CSS是什么及其继承与选择器
  2. 城市问题(Floyd)
  3. RMAN备份及恢复归档日志的语法
  4. 基于 CODING 的 Spring Boot 持续集成项目
  5. ipv6正则表达式 java,用正则表达式解析IPv4跟IPv6地址字符串
  6. python入门经典100题-零基础学习Python开发练习100题实例(1)
  7. c语言中的循环移位函数,C ++中循环移位(旋转)操作的最佳实践
  8. iOS 14.7 中的所有新功能
  9. docker stats 监控资源使用情况
  10. 计算机中 加减运算 的 实现原理
  11. web 服务器有哪些
  12. Excel中使用条件格式(比较两列将内容不同用颜色标识)
  13. 解决报错:SSL certificate problem: certificate has expired
  14. My SQL 安装配置
  15. 从word中提取图片的三种方法
  16. 【友盟+】国庆假期旅游类APP使用报告(下)
  17. 卷积神经网络使用到的公式
  18. 学习笔记-----浅谈汇编指令CMP运行机制
  19. 工作中提高工作效率的几个思维模式
  20. JAVA通过拦截器实现IP黑名单

热门文章

  1. html表单注册功能的实现,仅一个form表单 js实现注册信息依次填写提交功能
  2. 颜水成团队开源VOLO:无需额外数据,首次在ImageNet上达到87.1%的精度
  3. Jeff Dean竟在谷歌成众矢之的!开除“论文不合格”AI伦理研究员,被1400名员工批斗...
  4. 英特尔90亿美元卖掉「起家业务」,SK海力士接盘
  5. 苹果接盘倒下的无人车公司:吴恩达旗下,曾估值2亿美元,CEO及大部分员工被裁...
  6. docker image镜像的发布
  7. java:方法覆盖与方法重载
  8. Git分支合并:Merge、Rebase的选择
  9. Android第三十一期 - 市面上所有引导页的效果
  10. .NET Core程序中使用User Secrets存储敏感数据