list - Python class constructor returns an empty value -


i'm writing python class based on list. constructor builds list based on 2 other lists passed parameters. logic roughly: copy list new instance, iterate on list b, adding entries , using others modify entries list a.

i've got 2 versions of constructor. in first, list , list b processed loops. decided clever; used comprehension replace loop adds list new instance.

the first version of constructor works perfectly. second version returns empty list, though can @ value of self in debugger before constructor ends, , see it's correct.

why happening, , can make second version work?

here code makes second version misbehave. copies list new instance, iterates on instance update data in dictionary represents items in list b. ba list a; getkey function (passed parameter) derives dictionary key list element; _dictb dictionary contains element each element in list b.

self = [ [bae,none] bae in ba ]  # copy list self n in xrange(0,len(self)) :       # iterate on list b     _key = getkey( self[n][0])     if _dictb.has_key(_key) :         _dictb[_key] = n 

in first version, works, code above replaced this; operations performed , meanings of variables same:

for bae in ba :     _key = getkey(bae)     if _dictb.has_key(_key) :         _dictb[_key] = len(self)     self.append( [bae,none] ) 

i assume you're talking python constructors here , have, weird reason, omitted class definition , def __init__ statement. in "second version," first code snippet gave, first line assigns list local variable named "self". not replace object being constructed different object. thing gets returned constructor new object, not variable self.

solution: don't assign self. ever. don't think it.

also can't use list comprehension create subclass of list, instance of list. "first version" (second code snippet) works , there nothing wrong it.

aside: should replace "_dictb.has_key(key)" "key in _dictb."


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -