【发布时间】:2017-08-02 03:20:28
【问题描述】:
我在尝试调用类中定义的函数时遇到了 TypeError 类型的问题。错误是:TypeError: p() takes exactly 1 argument (2 given)
class HTMLGen:
def p(text):
return ("<p>%s</p>" % text)
def a(text):
return ("<a>%s</a>" % text)
def b(text):
return ("<b>%s</b>" % text)
def title(text):
return ("<title>%s</title>" % text)
def comment(text):
return ("<!--%s-->" % text)
def div(text):
return ("<div>%s</div>" % text)
def span(text):
return ("<span>%s</span>" % text)
def body(text):
return ("<body>%s</body>" % text)
然后,在导入 HTMLGen 类并尝试以这种方式使用 HTMLGen.p(t) 函数之后
>>> import htmlgen
>>> website = htmlgen.HTMLGen()
>>> paragraph = website.p("Hello World!")
然后按 Enter,我收到上述错误。有谁知道为什么 HTMLGen.p() 和其他函数得到多个参数,以及防止这种情况发生的最简单方法是什么?
【问题讨论】:
-
类中的方法总是在
self加上你给它的任何其他参数传递。self加上text是两个参数,但您的方法只接受 一个 参数。将self添加到所有这些或使它们成为静态函数。你为什么要把这个放在课堂上? -
考虑到
website.p("Hello World!")大致相当于HTMLGen.p(website, "Hello World!"),您就会明白为什么需要使用两个参数来定义该方法。