[英]Passing arguments to a function in Python
I'm not sure why I'm getting the message error我不确定为什么会收到消息错误
TypeError: __init__() takes exactly 3 arguments (4 given) TypeError: __init__() 正好接受 3 个参数(给定 4 个)
for the code described below:对于下面描述的代码:
class Worker(object):
def __init__(arg1,arg2,arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def some_function(self):
print "it works: " + arg1 + arg2 + arg3
w=Worker("a","b","c")
w.some_function()
What could I be missing?我可能会错过什么?
It should be def __init__(self, arg1,arg2,arg3):
.它应该是def __init__(self, arg1,arg2,arg3):
。 You'll also need to change the print
statement in some_function
to您还需要将some_function
中的print
语句更改为
print "it works: " + self.arg1 + self.arg2 + self.arg3
def __init__(self,arg1,arg2,arg3):
The first argument expected for any class function should always be self
.任何类函数的第一个参数应该始终是self
。
Well, the name is unimportant, but that's the meaning of it.好吧,名字并不重要,但这就是它的意思。
So your function definintion should look like:所以你的函数定义应该是这样的:
def __init__(self,arg1,arg2,arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.