【问题标题】:Python error in calling the function调用函数时出现 Python 错误
【发布时间】:2014-01-24 16:51:52
【问题描述】:

我有一个类有这两种方法:

  def whatIsYourName(self):
        print 'my name is class A'
    def whatIsYourName(self, name):
        print 'my name is {0}, I am class A'.format(name)

我可以打电话给第二个。但是当我这样称呼第一个时:

x = myClass()
x.whatIsYourName()

我收到了这个错误:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: whatIsYourName() takes exactly 2 arguments (1 given)

我使用的是 python 2.7

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    Python 不支持方法重载。最后定义的方法会覆盖之前定义的所有同名方法。

    但是,您可以利用多方法模式来实现这一点。请参考Guido's post

    【讨论】:

      【解决方案2】:

      您正试图重载一个方法。 whatIsYourName(self)whatIsYourName(sel,name) 覆盖。如果您是 C++/Java 程序员,这对您来说可能听起来很正常,但不幸的是 Python 就不一样了。如果要显示名称,请尝试在构造函数中定义它并打印它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-02
        • 2011-01-08
        • 2020-08-08
        相关资源
        最近更新 更多