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

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Fri Aug 26 15:15:05 CEST 2005



Jan Eden a écrit :
> 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.

Well, I prefer the use of "None" for that, as it cannot be mixed up with
any other value:

def Children(self, id=None, level=2):
  if id is None: id = self.id

Another possibility (mainly if you have many such arguments) is the use
of something like:

def Children(self, **kwords):
  id = kwords.pop("id", None)
  level = kwords.pop("level", 2)

Although it is not equivalent ! In the second cases, you have to name
the parameter to set it ! But I sometimes find this A Good Thing (tm)
when no argument order is better ...

Pierre

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68


More information about the Tutor mailing list