在Python中设置默认参数并覆盖相同的语法查询

在Python中设置默认参数并覆盖相同的语法查询,python,string-substitution,Python,String Substitution,以下是相关代码的片段: 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): use

以下是相关代码的片段:

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)
定义write_表单时,我们将文本的默认值设置为空字符串,我理解这一点

我感到困惑的是最后一行
self.write\u form(encode)
我们没有明确说明我们现在正在将变量文本设置为encode(或我们想要传递的任何内容…)

这是否意味着,由于我们只有一个变量(不包括self),我在python中传递的任何内容都将假定它是我为“text”传递的内容

提前谢谢

更新

使用jamylak的答案,我自己在一个简化版本中尝试了它(Python2.7,因为我不使用3)来得到我的答案。对于像我这样的N00B,这可能会让答案更清楚一些:

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

example()
>>>42

example(87)
>>>87

example("hello")
>>>"hello"

是的,
self
是在调用实例的方法时隐式传递的,默认参数不必总是用名称指定(如果以正确的顺序传递)。另一方面,python 3允许您使用星号(
*
)来确保将它们与名称一起传递:

>>> 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')
def foo(*,text=''): 通过 >>>foo('aa') 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 foo('aa') TypeError:foo()接受0个位置参数,但给出了1个 >>> >>>foo(text='aaa')
您的第一个参数是
self
,它由python自动传递给该函数。第二个参数
rot13
被传递到
text
。如果你传递第三个参数,你会得到一个错误