我已经查过了this post和 this post ,但找不到解决我的代码问题的好方法。
我有一个代码如下:
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)
然后我创建“f”并调用“fun”函数:f = foo([1, 2, 3, 4], "March", "June")
print(f.fun())
输出是:([1, 4, 9, 16], 'h', 4)
这是正确的,但如果我这样做:print(f.fun("April"))
我收到以下错误:TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
显然,python 将字符串参数“April”与列表混淆,我该如何解决?
最佳答案
默认情况下,传递给函数的第一个参数将分配给第一个参数。如果要将第一个参数分配给第二个(或 n:th)参数,则必须将其作为关键字参数提供。看,例如
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
参数的类型无关紧要,重要的是您在函数定义中使用的顺序。术语注释
关于python - 具有多个不同类型的可选参数的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64723092/