代碼解讀基于DJango1.5.1
https://github.com/django/django.git
如果你喜歡的話,可以把元類稱為“類工廠”(不要和工廠類搞混了:D) type就是Python的內建元類,當然了,你也可以創建自己的元類。
What is a metaclass in Python?
signal dispatching
from django.db.models.signals import m2m_changed
def toppings_changed(sender, **kwargs):
# Do something
pass
m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)
>>> p = Pizza.objects.create(...)
>>> t = Topping.objects.create(...)
>>> p.toppings.add(t)
the arguments sent to a m2m_changed handler (toppings_changed in the example above) would be:
Argument Value
sender Pizza.toppings.through (the intermediate m2m class)
instance p(the Pizza instance being modified)
action "pre_add"(followed by a separate signal with "post_add")
reverse False(Pizza contains the ManyToManyField(so this call modifies the forward relation)
model Topping(the class of the objects added to the Pizza)
pk_set {t.id}(since only Topping t was added to the relation)
using "default"(since the default router sends writes here)
Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None)
receiver function 有時候也被稱為signal handler
Python中的類變量和成員變量
可以發現:python的類變量和C++的靜態變量不同,并不是由類的所有對象共享。類本身擁有自己的類變量(保存在內存),當一個TestClass類的對象被構造時,會將當前類變量拷貝一份給這個對象,當前類變量的值是多少,這個對象拷貝得到的類變量的值就是多少;而且,通過對象來修改類變量,并不會影響其他對象的類變量的值,因為大家都有各自的副本,更不會影響類本身所擁有的那個類變量的值;只有類自己才能改變類本身擁有的類變量的值
如何理解 Python 的 Descriptor?
深入解析Python中的descriptor描述器的作用及用法
簡明Python魔法-1
簡明Python魔法-2