Differences between revisions 2 and 3
Revision 2 as of 2005-09-06 04:22:34
Size: 1265
Editor: ZoomQuiet
Comment:
Revision 3 as of 2009-12-25 07:18:49
Size: 1261
Editor: localhost
Comment: converted to 1.6 markup
Deletions are marked like this. Additions are marked like this.
Line 4: Line 4:
返回::'''[wiki:self/PyIAQ  Python 罕见问题集]''' 返回::'''[[self:PyIAQ|Python 罕见问题集]]'''
Line 6: Line 6:
::-- ZoomQuiet [[[DateTime(2005-09-06T04:10:30Z)]]]
[[TableOfContents]]
::-- ZoomQuiet [<<DateTime(2005-09-06T04:10:30Z)>>]
<<TableOfContents>>

返回::Python 罕见问题集

::-- ZoomQuiet [2005-09-06 04:10:30]

1. 问:创建对象很爽,但是如何更新?

Q: That's great for creating objects; How about for updating?

字典对象已经升级,现在可使用 d.update(Dict(a=100, b=200)) 来更新字典;

但是其它对象还没有对应的处理,所以你得自个儿来: obj.a = 100; obj.b = 200 当然也可以定义函式来进行更新,比如说:

Well, dictionaries have an update method, so you could do d.update(Dict(a=100, b=200)) when d is a dictionary. There is no corresponding method for objects, so you have to do obj.a = 100; obj.b = 200. Or you could define one function to let you do update(x, a=100, b=200) when x is either a dictionary or an object:

   1 import types
   2 
   3 def update(x, **entries):
   4     if type(x) == types.DictType: x.update(entries)
   5     else: x.__dict__.update(entries)
   6     return x

This is especially nice for constructors:

同位素版本:)

   1       def __init__(self, a, b, c, d=42, e=None, f=()):
   2         update(self, a=a, b=b, c=c, d=d, e=e, f=f)

PyIAQ/Q9 (last edited 2009-12-25 07:18:49 by localhost)