使用python的类报错TypeError: say() takes exactly 2 arguments (3 gi,pythontypeerror,Python写了下面的代
使用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()
编橙之家文章,
相关内容
- 为什么我列表最后一项没有遍历到呢?,列表,为何遍历
- Python语言中有没有rsync库,Python语言rsync库,请问python有
- 参考书中python2中的builtwith模块操作,返回HTTP Error 414:,
- Python异常处理应该由谁来做,Python异常处理,想问一个普
- Python源码中三引号作用是什么,python源码引号作用,pr
- Pthon脚本运行慢如何优化,pthon脚本优化,请大神们分析
- Python Django方法数据获取问题求助,pythondjango,Django中E
- Python2.7 module object has no attribute socket是什么问题,pyth
- Mac Python文件夹2.7删除后用pip安装Django出错,如何调整,
- 求Python3.3比较距离完成对应点对匹配改进方法,python
评论关闭