Python 2.7 调用函数时出现Python错误

Python 2.7 调用函数时出现Python错误,python-2.7,Python 2.7,我有一个类有以下两种方法: 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 (mos

我有一个类有以下两种方法:

  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不支持方法重载。最后定义的方法将覆盖前面定义的具有相同名称的所有方法


但是,您可以使用多方法模式来实现这一点。请参阅

您正在尝试重载一个方法。你的名字被你的名字压得喘不过气来。如果您是C++/Java程序员,这听起来可能很正常,但不幸的是,Python与此不同。如果要显示名称,请尝试在构造函数中定义名称并将其打印出来