[Tutor] Instance attribute as a parameter's default value

Kent Johnson kent37 at tds.net
Fri Aug 26 15:32:02 CEST 2005


Jan Eden wrote:
> Hi,
> 
> Jan Eden wrote on 26.08.2005:
> 
> 
>>Hi,
>>
>>I need to use an instance attribute as the default value for a parameter to a 
>>method.
>>
>>This obviously won't work:
>>
>>page.Children()
>>
>>def Children(self, id=self.id, level=2):
>>
>>How can I get the id parameter to use the attribute page.id? I know I could 
>>simply use the method call
>>
>>page.Children(id=page.id)
>>
>>but I thought it is much more elegant to use a default value here.
>>
>>Is it possible?
> 
> 
> Addition: I do use
> 
> def Children(self, id=0, level=2):
>     if not id: id = self.id
> 
> right now. But still - there has to be a smarter way.

Other than using None instead of 0 as Pierre suggests, this is the best way. The problem is that the default argument is bound when the function definition is executed, so the value has to be defined at that time and it is then fixed. To use a (changeable) attribute as the default you have to read it when the function body is executed.

Kent



More information about the Tutor mailing list