469,646 Members | 1,628 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,646 developers. It's quick & easy.

Default parameter for a method... again

I had posted this before but all the spam whipped it out...

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 thereturn 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.
Jun 27 '08 #1
1 886
On Apr 16, 9:26 am, s0s...@gmail.com wrote:
I had posted this before but all the spam whipped it out...

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 thereturn 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.
That is the straightforward way. It may not seem that way now but all
languages have patterns and this is a common one in python. You will
see code like this all over Python, even in the standard library. The
best thing to do is embrace it. It will not only work, but make your
code more readable to others.

Matt
Jun 27 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

26 posts views Thread by Alex Panayotopoulos | last post: by
18 posts views Thread by Dan Cernat | last post: by
7 posts views Thread by A.M | last post: by
74 posts views Thread by Zytan | last post: by
6 posts views Thread by s0suk3 | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.