Reputation: 455
I have already checked this post and this post, but couldn't find a good way of sorting the problem of my code out.
I have a code as follows:
class foo:
def __init__(self, foo_list, str1, str2):
self.foo_list = foo_list
self.str1 = str1
self.str2 = str2
def fun(self, l=None, s1=None, s2=None):
if l is None:
l = self.foo_list
if s1 is None:
s1 = self.str1
if s2 is None:
s2 = self.str2
result_list = [pow(i, 2) for i in l]
return result_list, s1[-1], len(s2)
Then I create "f" and call "fun" function:
f = foo([1, 2, 3, 4], "March", "June")
print(f.fun())
The output is:
([1, 4, 9, 16], 'h', 4)
which is correct, but if I do:
print(f.fun("April"))
I get the following error:
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
Apparently, python confuses the string argument "April" with the list, how do I fix it?
Upvotes: 5
Views: 1886
Reputation: 33988
By default, the first argument passed to the function will be assigned to the first parameter. If you want to assign the first argument to the second (or n:th) parameter, you must give it as keyword argument. See, for example
In [19]: def myfunc(x='X', y=5):
...: print(x,y)
...:
...:
# No arguments -> Using default parameters
In [20]: myfunc()
X 5
# Only one positional argument -> Assigned to the first parameter, which is x
In [21]: myfunc(100)
100 5
# One keyword argument -> Assigned by name to parameter y
In [22]: myfunc(y=100)
X 100
The type of the arguments do not matter, but the order you used in the function definition.
Upvotes: 5