user2418063
user2418063

Reputation: 83

Python default values for class member function parameters set to member variables

I am running into a problem writing recursive member functions in Python. I can't initialize the default value of a function parameter to be the same value as a member variable. I am guessing that Python doesn't support that capability as it says self isn't defined at the time I'm trying to assign the parameter. While I can code around it, the lack of function overloading in Python knocks out one obvious solution I would try.

For example, trying to recursively print a linked list I get the following code for my display function;

    def display(self,head = -1):
       if head == -1:
          head = self.head 

       if not head:
          return

       print head,

       self.display(head.link)

While this code works, it is ugly. The main function looks like this:

def main():
    l = List();
    l.insert(3);
    l.insert(40);
    l.insert(43);
    l.insert(45);
    l.insert(65);
    l.insert(76);

    l.display()

if __name__ == "__main__":
    main()

If I could set the display function parameter to default to self.head if it is called without parameters then it would look much nicer. I initially tried to create two versions of the function, one that takes two parameters and one that takes one but as I said, Python doesn't support overloading. I could pass in an argument list and check for the number of arguments but that would be pretty ugly as well (it would make it look like Perl!). The trouble is, if I put the line head = self.head inside the function body, it will be called during every recursive call, that's definitely not the behavior I need. None is also a valid value for the head variable so I can't pass that in as a default value. I am using -1 to basically know that I'm in the initial function call and not a recursive call. I realize I could write two functions, one driving the other but I'd rather have it all self contained in one recursive function. I'm pretty sure I'm missing some basic pythonic principle here, could someone help me out with the pythonic approach to the problem?

Thanks!

Upvotes: 4

Views: 3018

Answers (1)

Marcin
Marcin

Reputation: 49866

I don't really see what's wrong with your code. If you chose a falsy default value for head, you could do: head = head or self.head which is more concise.

Otherwise, this is pretty much what you have to do to handle default arguments. Alternatively, use kwargs:

def display(self,**kwargs):
    head = kwargs.get("head", self.head)

    if not head:
        return

    print head,

    self.display(head=head.link) # you should always name an optional argument,
                                 # and you must name it if **kwargs is used.

Upvotes: 3

Related Questions