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)
我确定我做得正确......
答案 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