一、类和对象
Python属于动态类型的语言,而动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时创建的,而是运行时动态创建的,比方说我们要定义一个 Person
的class,就写一个 Person.py
模块:
1
2
3
4
5
6
7
8
|
# -*- coding: utf-8 -*- # 文件名 : Person.py class Person( object ): def say( self , s = '元类' ): print ( '今日学习:%s' % s) if __name__ = = '__main__' : p = Person() p.say() |
当Python解释器载入 Person
模块时,就会依次执行该模块的所有语句,执行结果就是动态创建出一个 Person
的class对象,测试如下,(注意,是引入一个Person.py脚本)
1
2
3
4
5
6
7
8
9
10
11
|
# 文件名 :测试.py # 引入模块,需要模块的路径 from Person import Person # 创建一个Person类的实例 p = Person() p.say( 'Python中的元类' ) # 调用say方法 # 今日学习:Python中的元类 print ( type (p)) # 把实例 p 的类型打印出来 # <class 'say.Person'> print ( type (Person)) # Person 类的类型打印出来 # <class 'type'> |
这里是用来 type()
函数,可以查看一个类型或变量,的类型, Person
是一个class,它的类型就是 type
,而 p
是一个实例,它的类型就是class Person
。
二、type类
我们说class的定义是运行时动态创建的,而创建class的方法就是使用 type()
函数
type()
函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过 type()
函数创建出Person 类,而无需通过 class Person(object)...
的定义,此时type的第二种用法,我们只要type传object是可以返回该对象类型的,但是当我们的type存在三位参数存在时
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# type 类 class type ( object ): """ type(object_or_name, bases, dict) type(object) -> the object's type type(name, bases, dict) -> a new type """ #参数介绍 """ type(object_or_name, bases, dict) object-or-name -- 对象或类的名称。 bases -- 基类的元组。 dict -- 字典,类内定义的命名空间变量。 """ # 返回新的类型对象。 |
1
2
3
4
5
6
7
8
9
10
11
12
|
# -*- coding: utf-8 -*- def fun( self , s): print ( 'hello' + s) Hello = type ( 'hello' , ( object ,), dict (func = fun)) if __name__ = = '__main__' : h = Hello() h.func( ' word' ) # hello word print ( type (h)) # <class '__main__.hello'> print ( type (Hello)) # <class 'type'> |
我们通过 type()
函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用 type()
函数创建出class
在正常情况下,我们都用 class Xxx...
来定义类,但是, type()
函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同,要在静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会非常复杂
三、元类Metaclass
除了使用 type()
动态创建类以外,要控制类的创建行为,还可以使用metaclass
,也就是元类
当我们定义了类以后,就可以根据这个类创建出实例,所以:先定义类,然后创建实例
但是如果我们想创建出类呢?那就必须根据metaclass创建出类,所以:先定义metaclass
,然后创建类,元类就是用来创建这些类(对象)的,元类就是类的类
我们先看一个简单的例子,这个metaclass
可以给自定义的类增加一个 add
方法定义 ListMetaclass
,按照默认习惯,metaclass的类名总是以Metaclass结尾,以便清楚地表示这是一个metaclas。
四、自定义一个元类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class UpperMetaclass( type ): def __new__(mcs, class_name, class_parents, class_attrs): new_attrs = {} for name, value in class_attrs.items(): if not name.startswith( '__' ): # 判断是否为非私有属性 new_attrs[name.upper()] = value # 直接调用type 来创建一个类 return type .__new__(mcs, class_name, class_parents, class_attrs) # 测试 class Emp( object , metaclass = UpperMetaclass): name = '张三' acl = 500 if __name__ = = '__main__' : print ( hasattr (Emp, 'name' )) # 判断Emp中是否有名字为name print ( hasattr (Emp, 'NAME' )) # 判断Emp中是否有名字为NAME |
到此这篇关于Python深入浅出分析元类的文章就介绍到这了,更多相关Python元类内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://aweia.blog.csdn.net/article/details/125622997