Question

Here's the segment of relevant code:

class MainPage(webapp2.RequestHandler):
    def write_form(self,text=""):
        self.response.out.write(form%{"text":escape_html(text)}) #form is a html form

    def get(self):
        self.write_form()

    def post(self):
        user_input = self.request.get('text') #from a html form
        encode = user_input.encode('rot13')
        self.write_form(encode)

When write_form is defined, we set the default value of text to be the empty string, I understand this.

Where I'm confused is the last line self.write_form(encode)we're not explicitly stating that we are now setting the variable text to encode (or whatever we want to pass in...).

Does this mean that as we only have one variable (not counting self) that whatever I pass in python will assume it to be what I am passing in for 'text'?

Thanks in advance

Update

Using jamylak's answer, I tried it for myself (python 2.7 as I don't use 3) in a simplified version to get my answer. For n00bs like me this might make the answer a bit clearer:

def example(result="42"):
    print result

example()
>>>42

example(87)
>>>87

example("hello")
>>>"hello"
Was it helpful?

Solution

Yes, self is passed implicitly when you call the method of an instance and default arguments need not always be specified with their names(if passed in the correct order). On a side note python 3 allows you to use the asterisk (*) to make sure that you pass them with their names:

>>> def foo(*, text=''):
        pass

>>> foo('aa')
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    foo('aa')
TypeError: foo() takes 0 positional arguments but 1 was given
>>> 
>>> foo(text='aaa')

OTHER TIPS

your first argument is self which is passed to that function automatically by python. Second argument rot13 is passed to text. If you pass a third argument you will get an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top