python里除了继承修改类之外还有装饰器也能

来源:互联网 发布:ant java 编辑:程序博客网 时间:2024/05/21 17:40

python是面向对象的语言,它有类的继承,因此它是可以修改基类函数的功能。但是除了继承之外,类函数的功能也可以使用装饰器来修改,这种功能叫做装饰类。为了学习装饰类,需要好好地查看下面的代码:

#python 3.6#定义装饰器函数def decorator(aClass):    class newClass:        def __init__(self, age):            self.total_display   = 0            self.wrapped         = aClass(age)        def display(self):            self.total_display += 1            print("total display: ", self.total_display)            self.wrapped.display()    return newClass#对类使用装饰器@decoratorclass Blog:    def __init__(self, age):        self.age = age    def display(self):        print("http://blog.csdn.net/caimouse age is", self.age)#创建类对象myBlog = Blog(15)for i in range(3):    myBlog.display()
结果输出如下:

total display:  1
http://blog.csdn.net/caimouse age is 15
total display:  2
http://blog.csdn.net/caimouse age is 15
total display:  3
http://blog.csdn.net/caimouse age is 15
在这个例子里可以看到,定义了一个装饰器类的函数decorator,然后在它内部定义了一个类,这个类的方法与要被装饰类的方法一样名称。接着装饰函数返回这个类的类型,这个类型就可以拿来装饰别的类了。它的语法与使用装饰函数是一样的。

Python游戏开发入门

http://edu.csdn.net/course/detail/5690

你也能动手修改C编译器

http://edu.csdn.net/course/detail/5582

纸牌游戏开发

http://edu.csdn.net/course/detail/5538 

五子棋游戏开发

http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246
WiX安装工具的使用
http://edu.csdn.net/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810
TensorFlow API攻略
http://edu.csdn.net/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通 
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590
在Windows下SVN的版本管理与实战 
http://edu.csdn.net/course/detail/2579
Visual Studio 2015开发C++程序的基本使用 
http://edu.csdn.net/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn.net/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn.net/course/detail/2672



阅读全文
0 0
原创粉丝点击