GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Python-1/python12/5.md at master · hackNeo/Python-1

Expand file tree

/

5.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
33 lines (20 loc) · 1.77 KB
/

5.md

Copy path

File metadata and controls

33 lines (20 loc) · 1.77 KB
Raw
Copy raw file
Download raw file
Edit and raw actions

五、使用元类

终于到了使用元类了,可是一般来说,我们根本就用不上它,就像Python 界的领袖 Tim Peters 说的:

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

元类的主要用途是创建 API。一个典型的例子是 Django ORM。它允许你像这样定义:

class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

但是如果你这样做的话:

guy  = Person(name='bob', age='35')
print guy.age

这并不会返回一个 IntegerField 对象,而是会返回一个 int,甚至可以直接从数据库中取出数据。这是有可能的,因为 models.Model 定义了 __metaclass__ , 并且使用了一些魔法能够将你刚刚定义的简单的Person类转变成对数据库的一个复杂 hook。Django 框架将这些看起来很复杂的东西通过暴露出一个简单的使用元类的 API 将其化简,通过这个 API 重新创建代码,在背后完成真正的工作。

Python 中的一切都是对象,它们要么是类的实例,要么是元类的实例,除了 type。type 实际上是它自己的元类,在纯 Python 环境中这可不是你能够做到的,这是通过在实现层面耍一些小手段做到的。

参考:

https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python

最后如果对本文有兴趣,可以关注公众号:

公众号

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.