使用python的类报错TypeError: say() takes exactly 2 arguments (3 gi,pythontypeerror,Python写了下面的代


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() 只有两个参数啊

具体的,@蓝皮鼠 已经说的很清楚了!我想补充一下,self参数其实就是实例本身。python为每一个非静态方法绑定到相应的实例中,但是self并不是python的关键字
所以,你可以将self替换为任何合法的名字。

class Human:    def say(Tedd,tell, text):        print '@%s %s' % (tell, text)p = Human()p.say('Paul', 'hello')

所以,其实上面的self参数就是实例本身就有点不妥了,我觉得应该这样说:非静态方法的第一个参数是实例本身。

类中的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()

编橙之家文章,

评论关闭