473,803 Members | 3,166 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Default parameter for a method

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.
Jun 27 '08 #1
6 1468
s0****@gmail.co m 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 "straightforwar d" than that.

-Larry
Jun 27 '08 #2

On Wed, 2008-04-16 at 13:47 -0500, Larry Bates wrote:
s0****@gmail.co m 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 "straightforwar d" 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.
Regards,
Cliff
Jun 27 '08 #3
Cliff Wells wrote:
>
On Wed, 2008-04-16 at 13:47 -0500, Larry Bates wrote:
>s0****@gmail.co m 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 "straightforwar d" 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

Jun 27 '08 #4
s0****@gmail.co m 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:
....
>
def meth2(self, arg=meth1()):
Not good. If the default value of an argument is mutable, there
are wierd effects, because the default value is bound once when the
class is created, then shared between all later uses. This is almost
never what was wanted or intended, and it's a common source of subtle
bugs.

In general, default values should be immutable constants only.
There's been talk of fixing this (it's really a design bug in Python),
but for now, it's still broken.

(I just had horrible thoughts about the implications of binding
a closure to a default argument. You don't want to go there.)

John Nagle
Jun 27 '08 #5

"John Nagle" <na***@animats. comwrote in message
news:48******** *************** @news.sonic.net ...
| s0****@gmail.co m 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:
| >
| ...
|
| >
| def meth2(self, arg=meth1()):
|
| Not good. If the default value of an argument is mutable, there
| are wierd effects, because the default value is bound once when the
| class is created, then shared between all later uses. This is almost
| never what was wanted or intended, and it's a common source of subtle
| bugs.
|
| In general, default values should be immutable constants only.

Then one would have to restrict default args to immutable builtins.
There is no way to determine (without reading code) whether instances of a
user-defined class are mutable or not.

tjr

Jun 27 '08 #6
On Apr 16, 4:21*pm, John Nagle <na...@animats. comwrote:
In general, default values should be immutable constants only.
This is more restrictive than necessary; it should rather read "In
general, default values should be *treated as* immutable objects
only". It's perfectly fine for a default value to be mutable if the
function doesn't modify it, as in the following example:

def parse(text, stopwords=set(w .strip() for w in
open('stopwords .txt')):
words = [w for w in text.split() if w not in stopwords]
...

Since the set is not modified, there's no harm for being mutable; IOW
it's no different than using a frozenset instead. Similarly for dicts,
lists and other mutable containers, as long as they are treated as
read-only.

George
Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
15579
by: Alex Panayotopoulos | last post by:
Hello all, Maybe I'm being foolish, but I just don't understand why the following code behaves as it does: - = - = - = - class listHolder: def __init__( self, myList= ): self.myList = myList
18
7846
by: Dan Cernat | last post by:
Hi there, A few threads I had a little chat about default values. I am starting this thread because I want to hear more opinions about the default values of function parameters. Some say they see no use of them. Others say thar they are bad. I like them. So, could anyone tell me why they are in the standard? Are they bad? I do not intend to start war. Nor am I a troll.
18
2255
by: Clark Nu | last post by:
It seems that when I define a fuction,I can set a default value to some of the peremeters.When I call the fuction without some of them,the fuction will use the default value automaticlly then continue to work.But I'v fogot how to use,even I'v fogot whether I can use it in C# or not. Help me.
7
4233
by: Vyssokih Max | last post by:
Hello! In C++, I can wrote: void Update(int count = 0) {...} and use it without parameters or with one parameter
7
5329
by: A.M | last post by:
Hi, Do we have default method parameter in C#? Something like this void method1(int i = 12) { .... }
8
3047
by: cody | last post by:
Why doesn't C# allow default parameters for methods? An argument against I hear often is that the default parameters would have to be hardbaken into the assembly, but why? The Jit can take care of this, if the code is jitted the "push xyz" instructions of the actual default values can be inserted. To make things simpler and better readable I'd make all default parameters named parameters so that you can decide for yourself why one to...
4
12663
by: indigator | last post by:
I have an ASP.Net web service class, DataLayer.asmx.cs. I have two constructors for the DataLayer class. One is the default parameter-less one and the second one accepts a string argument. When I am trying to consume this web service from another asp.net application, only the default parameter-less constructor shows up. And if i try creating an instance of the second constructor, it gives me a compiler error saying that No overload of...
14
3276
by: cody | last post by:
I got a similar idea a couple of months ago, but now this one will require no change to the clr, is relatively easy to implement and would be a great addition to C# 3.0 :) so here we go.. To make things simpler and better readable I'd make all default parameters named parameters so that you can decide for yourself which one to pass and which not, rather than relying on massively overlaoded methods which hopefully provide the best...
1
1016
by: s0suk3 | last post by:
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
0
9703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10317
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9125
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6844
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5501
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3799
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2972
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.