【发布时间】:2010-07-09 18:08:40
【问题描述】:
来源
from copy import deepcopy
class Field(object):
def __init__(self):
self.errors = []
class BaseForm(object):
pass
class MetaForm(type):
def __new__(cls, name, bases, attrs):
attrs['fields'] = dict([(name, deepcopy(attrs.pop(name))) for name, obj in attrs.items() if isinstance(obj, Field)])
return type.__new__(cls, name, bases, attrs)
class Form(BaseForm):
__metaclass__ = MetaForm
class MyForm(Form):
field1 = Field()
f1 = MyForm()
f1.fields['field1'].errors += ['error msg']
f2 = MyForm()
print f2.fields['field1'].errors
输出
['error msg']
问题
为什么会这样输出?我以为我在修改之前克隆了错误列表,它们不应该都引用同一个列表?
【问题讨论】:
-
看起来
MetaForm.__new__只为MyForm调用一次(为Form调用一次)即使我已经构造了 twoMyForms。这是如何运作的?我的理解是每次构建时都需要调用它。我猜它在班级层面上运作?那么移动deepcopy语句的最佳位置在哪里?