Python的元编程案例
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.什么是元编程
元编程概念来自LISP和smalltalk。
我们写程序是直接写代码,是否能够用代码来生成未来我们需要的代码吗?这就是元编程。
例如,我们写一个类class A,能否用代码生成一个类出来?
用来生成代码的程序称为元程序metaprogram,编写这种程序就称为元编程metaprogramming。
Python语言能够通过反射实现元编程。
Python中所有非object类都继承自object类 所有类的类型包括type类都是type type类继承自object类,object类的类型也是type类
二.type类
1>.查看type的构造方法
2>.使用type构造一个新类型(可以借助type构造任何类,用代码来生成代码,这就是元编程)
1 #!/usr/bin/env python 2 #_*_conding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie 5 6 def __init__(self,name,age): 7 self.name = name 8 self.age = age 9 10 def show(self): 11 print(self.__dict__) 12 13 student = type("Student",(object,),{"school_address":"北京","__init__":__init__,"show":show}) 14 15 print(student) 16 print(student.__dict__) 17 print(student.__base__) 18 print(student.mro()) 19 20 student("jason",18).show()
<class '__main__.Student'> {'school_address': '北京', '__init__': <function __init__ at 0x1006a2e18>, 'show': <function show at 0x10215fae8>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None} <class 'object'> [<class '__main__.Student'>, <class 'object'>] {'name': 'jason', 'age': 18}