2 Replies - 1157 Views - Last Post: 28 February 2013 - 01:21 AM Rate Topic: -----

#1 Static Hazard  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 25-November 09

Parameters defaulting to None

Posted 27 February 2013 - 09:57 PM

In my constructor, the name and description parameters are supposed to default to None if they are not entered. I think I have that part set up correctly. If name isn't entered and defaults to None, a ValueError is thrown:

    def __init__(self, name = None, methodCount, locCount, description = None):
        
        if(name == None):
            raise ValueError("Stats.__init__: invalid parm")
        else:
            self.theName = name
            
        if(description != None):
            self.theDescription = description
            
        self.theMethodCount = methodCount
        self.theLocCount = locCount



My question is, how does my constructor know which parameters are left out? I know Python is dynamically typed, so if I left out the name, wouldn't it think that methodCount is actually name? How would I pass this?

myStats = stats.Stats(3,15)



Would it automatically, from the statement above, set name and description to None?

This post has been edited by Static Hazard: 27 February 2013 - 09:59 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Parameters defaulting to None

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4187
  • View blog
  • Posts: 11,845
  • Joined: 18-April 07

Re: Parameters defaulting to None

Posted 27 February 2013 - 11:13 PM

You shouldn't be able to do that because no non-default arguments can follow a default argument. Just because of your question scenario. If you follow a default with a none default does it know that you are specifying a value for the default or not?

So you will want a signature like this...

def __init__(self, methodCount, locCount, name = None, description = None):



That way you have to specify methodCount and locCount and can leave off the other two. You can also use the name of the argument during the call to set a default parameter even if it is listed later in the signature. For instance if you call your method with description = 'some descript' it will set that even if you haven't specified a name.

Hopefully that is clear enough for you. :)
Was This Post Helpful? 1
  • +
  • -

#3 Static Hazard  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 25-November 09

Re: Parameters defaulting to None

Posted 28 February 2013 - 01:21 AM

That makes perfect sense. I was getting a non-default argument error from my code, and now I know why. Thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1