Python写了下面的代码:
class Human: def say(tell, text): print '@%s %s' % (tell, text)p = Human()p.say('Paul', 'hello')
运行后报错,提示:
Traceback (most recent call last): File "Untitled.py", line 6, in <module> p.say('Paul', 'hello')TypeError: say() takes exactly 2 arguments (3 given)
可是我的 say() 只有两个参数啊
解决方案
类中的method必须附带一个参数self,它会在你调用的时候被解释器隐式传入
定义成这样
def say(self,tell, text): print '@%s %s' % (tell, text)
如果你需要让它成为一个类方法而不是实例方法,可以用staticmethod装饰器来装饰它
贴哥示例你看下,参数是如何隐式传递的
class Test(object): @staticmethod def foo(): print "foo" def bar(self): print "bar"t = Test()Test.bar(t)t.bar()t.foo()Test.foo()