GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing raw.githubusercontent.com — raw.githubusercontent.com # 三、什么是元类 #
通过上面的介绍,终于模模糊糊的带到元类这里来了。可是我们到现在还不知道元类是什么东东。
我们创建类的时候,大多数是为了创建类的实例对象。那么元类呢?元类就是用来创建类的。也可以换个理解方式就是:元类就是类的类。
通过上面 `type()` 函数的介绍,我们知道可以通过 `type()` 函数创建类:
```python
MyClass = type('MyClass', (), {})
```
实际上 `type()` 函数是一个元类。`type()` 就是 Python 在背后用来创建所有类的元类。
那么现在我们也可以猜到一下为什么 `type()` 函数是 type 而不是 Type呢?
这可能是为了和 str 保持一致性,str 是用来创建字符串对象的类,而 int 是用来创建整数对象的类。type 就是创建类对象的类。你可以通过检查 `__class__` 属性来看到这一点。Python 中所有的东西,注意喔,这里是说所有的东西,他们都是对象。这包括整数、字符串、函数以及类。它们全部都是对象,而且它们都是从一个类创建而来。
```python
# 整形
age = 23
print(age.__class__)
# 字符串
name = '两点水'
print(name.__class__)
# 函数
def fu():
pass
print(fu.__class__)
# 实例
class eat(object):
pass
mEat = eat()
print(mEat.__class__)
```
输出的结果如下:
```
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |