Quick Filter Dictionary
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Mar 14 08:28:45 EDT 2007
abcd a écrit :
> On Mar 14, 7:29 am, "abcd" <codecr... at gmail.com> wrote:
>> Hi,
>> I have a dictionary which may contain various keys/values, however,
>> it will always contain 'name' and 'age' keys.
>>
>> This dictionary is kept inside a class, such as....
>>
>> class Person:
Do yourself a favor : use new-style classes:
class Person(object):
>> def __init__(self, name, age):
>> self.data = {'name' : name, 'age' : age}
You may improve this part with kwargs:
def __init__(self, name, age, **kw):
kw.update(name=name, age=age)
self.data = kw
Also, and FWIW, object attributes are stored in self.___dict__. Do you
have a compelling reason to use yet another 'data' dict ?
>> def getData(self, includeNameAge=False):
>> if includeNameAge: return self.data
>> tmp = <shallow or deep copy of 'data'>
tmp = self.data.copy()
>> del tmp['name']
>> del tmp['age']
>> return tmp
The problem with this implementation (as well as for the other below) is
that in the first case you return a reference to the data dict itself,
while in the second case you return a new dict.
p = Person('bibi', 42, foo='bar')
data = p.getData(True)
data['baaz'] = 'quux'
del data['name']
print p.data
p = Person('bibi', 42, foo='bar')
p.getData()
data['baaz'] = 'quux'
del data['foo']
print p.data
Better to *always* return a copy IMHO.
More information about the Python-list
mailing list