方法不带参数

时间:2016-04-05 09:46:52

标签: python

class Person:
    def __init__(self, name):
        self.name = name
    def printName():
        print "my name is %s" % self.name

Mitchell = Person("Mitchell")
Mitchell.printName()

此代码抛出此错误:

Traceback (most recent call last):
  File "/home/mitch/Desktop/test.py", line 8, in <module>
    Mitchell.printName()
TypeError: printName() takes no arguments (1 given)

我确定我做得正确......

2 个答案:

答案 0 :(得分:0)

因为您忘记将self显式添加到printName实例方法。应该就像

def printName(self):
    ...

Python隐式地将对象实例传递给每个实例方法。虽然与问题没有直接关系,但在使用Python时尝试使用pep8约定。根据{{​​1}}函数名称是蛇形的,不是驼峰式的,因此是变量名称。所以使用pep8和`mitchell'来实现他们的骆驼和pascel-cased对应物。

答案 1 :(得分:0)

你错过了printName函数定义

中的自我参数
class Person:
    def __init__(self, name):
        self.name = name
    def printName(self):
        print "my name is %s" % self.name
相关问题