【问题标题】:Problems with class functions' arguments Python类函数参数 Python 的问题
【发布时间】: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!"),您就会明白为什么需要使用两个参数来定义该方法。

标签: python class arguments


【解决方案1】:

每当你在类内创建函数时,它必须在类内的所有函数中都有 self 参数。

class HTMLGen:
    def p(self,text):
        return ("<p>%s</p>" % text)
    def a(self,text):
        return ("<a>%s</a>" % text)
    def b(self,text):
        return ("<b>%s</b>" % text)
    def title(self,text):
        return ("<title>%s</title>" % text)
    def comment(self,text):
        return ("<!--%s-->" % text)
    def div(self,text):
        return ("<div>%s</div>" % text)
    def span(self,text):
        return ("<span>%s</span>" % text)
    def body(self,text):
        return ("<body>%s</body>" % text)

【讨论】:

  • 谢谢!我确实记得了解过 self 参数,但从未想过在这里使用它。
【解决方案2】:

您需要添加一个附加参数,按照惯例称为 self.它指的是对象本身。许多编程语言都使用关键字this

def span(self, text):
    return ("<span>%s</span>" % text)

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2014-02-06
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多