Default parameter for a method

Peter Otten __peter__ at web.de
Wed Apr 16 15:27:20 EDT 2008


Cliff Wells wrote:

> 
> On Wed, 2008-04-16 at 13:47 -0500, Larry Bates wrote:
>> s0suk3 at gmail.com wrote:
>> > I wanted to know if there's any way to create a method that takes a
>> > default parameter, and that parameter's default value is the return
>> > value of another method of the same class. For example:
>> > 
>> > class A:
>> >     def __init__(self):
>> >         self.x = 1
>> > 
>> >     def meth1(self):
>> >         return self.x
>> > 
>> >     def meth2(self, arg=meth1()):
>> >         # The default `arg' should would take the return value of
>> > meth1()
>> >         print '"arg" is', arg
>> > 
>> > This obviously doesn't work. I know I could do
>> > 
>> > ...
>> >     def meth2(self, arg=None):
>> >         if arg is None:
>> >             arg = self.meth1()
>> > 
>> > but I'm looking for a more straightforward way.
>> 
>> You can write this as:
>> 
>>      def meth2(self, arg=None):
>>          arg = arg or self.meth1()
>> 
>> IMHO - You can't get much more "straightforward" than that.
> 
> What if arg is 0 an empty list or anything else that's "False"?
> 
> def meth2(self, arg=None):
>     arg = (arg is not None) or self.meth1()
> 
> is what you want.

No, it's not:

>>> for arg in None, 0, "yadda":
...     print "---", arg, "---"
...     if arg is None: arg = "call method"
...     print "OP:", arg
...     print "Larry:", arg or "call method"
...     print "Cliff:", (arg is not None) or "call method"
...
--- None ---
OP: call method
Larry: call method
Cliff: True
--- 0 ---
OP: 0
Larry: call method
Cliff: True
--- yadda ---
OP: yadda
Larry: yadda
Cliff: True

Peter




More information about the Python-list mailing list