Confusion regarding constructor as default value
Steve Holden
steve at holdenweb.com
Thu Sep 27 10:03:10 EDT 2007
aine_canby at yahoo.com wrote:
> On 27 Sep, 15:03, aine_ca... at yahoo.com wrote:
>> Why are the following different?
>>
>> def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""),
>> ExpiryDate(""))):
>> # check to see if the row already exists, if not add it to the
>> container
>>
>> if not self.dict.has_key(rowName):
>> self.dict[rowName] = tableRow
>>
>> def AddRow(self, rowName, tableRow):
>> # check to see if the row already exists, if not add it to the
>> container
>>
>> if not self.dict.has_key(rowName):
>> self.dict[rowName] = TableRow(ReleaseDate(""), ExpiryDate(""))
>>
>> It seems that when I use the first function that I'm getting duplicate
>> objects in self.dict
>>
>> Thanks for your help,
>>
>> Aine.
>
> I've just tried the following:
>
> Function A:
>
> def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""),
> ExpiryDate(""))):
>
> print tableRow
> if not self.dict.has_key(rowName):
> self.dict[rowName] = tableRow
>
> Function B:
>
> def AddRow(self, rowName, tableRow=None):
>
> if tableRow==None:
> tableRow = TableRow(ReleaseDate(""), ExpiryDate(""))
> # check to see if the row already exists, if not add it to the
> container
> print tableRow
> if not self.dict.has_key(rowName):
> self.dict[rowName] = tableRow
>
> Function A is giving:
>
> <DatabaseExamination.TableRow instance at 0x011D4468>
> <DatabaseExamination.TableRow instance at 0x011D42B0> same!
> <DatabaseExamination.TableRow instance at 0x011D42B0> same!
> <DatabaseExamination.TableRow instance at 0x011D42B0> same!
> <DatabaseExamination.TableRow instance at 0x011D42B0> same!
>
> Function B is giving:
>
> <DatabaseExamination.TableRow instance at 0x011D0670>
> <DatabaseExamination.TableRow instance at 0x011D0760>
> <DatabaseExamination.TableRow instance at 0x011D07D8>
> <DatabaseExamination.TableRow instance at 0x011D0850>
>
>
> So at least I know know what is causing the problem. But I'm still not
> understanding why I can't use TableRow() as the default value in order
> to geterate new instances.
>
Because the value of the default is computed as the funciton declaration
is processed, whereas you seem to expect to see a new call to ExpiryDate
each time the function is called.
> How would you implement this?
>
> Thanks,
>
> Aine.
>
Function B is the canonical solution to this problem.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Sorry, the dog ate my .sigline
More information about the Python-list
mailing list