Python 元类

type()

可以获取对象类型:

1
2
3
4
5
6
7
8
class Student(object):
def action(self):
pass

s= Student()

print(type(s))
print(type(Student))

结果为:

1
2
<class '__main__.Student'>
<type 'type'>

传入 s ,它是实例,类型为 class Student

传入类名 Student ,它的类型就是 type

除了可以返回一个对象的类型,还能创建新的类型:

1
2
3
4
5
6
def play(self):
print 'lol'

Me = type('Me',(object,),dict(play=play))
zlf = Me()
zlf.play()

结果是: lol

type() 方法传入的三个参数依次是:

  1. 类名
  2. 父类
  3. 方法名

运行:

1
2
print type(zlf)
print type(Me)

结果和之前一样的:

1
2
<class '__main__.Me'>
<type 'type'>

直接用 class 创建类和使用 type() 函数其实是一样的,因为 Python 解释器就是用后者创建出 class 的。

metaclass

据说是 Python 中的最难理解的概念,也是 Python 中的 black magic 。

看了许多解释之后,只是能够知道一些模糊的概念:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
age = 23

print age.__class__
print age.__class__.__class__

name = 'zlf'

print name.__class__
print name.__class__.__class__

class Me(object):
def play(self):
pass

print Me.__class__
print Me.__class__.__class__

结果:

1
2
3
4
5
6
<type 'int'>
<type 'type'>
<type 'str'>
<type 'type'>
<type 'type'>
<type 'type'>

“元类就是深度的魔法,99% 的用户应该根本不必为此操心。如果你想搞清楚究竟是否需要用到元类,那么你就不需要它。那些实际用到元类的人都非常清楚地知道他们需要做什么,而且根本不需要解释为什么要用元类。” —— Python 界的领袖 Tim Peters

关于元类,Stack Overflow 上一个精彩的回答

该回答的中文翻译