具有多个不同类型的可选参数的调用函数

Cod*_*der 5 python python-3.x

我已经检查了这篇文章这篇文章,但找不到解决我的代码问题的好方法。

我有一个代码如下:

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)

Run Code Online (Sandbox Code Playgroud)

然后我创建“f”并调用“fun”函数:

f = foo([1, 2, 3, 4], "March", "June")
print(f.fun())
Run Code Online (Sandbox Code Playgroud)

输出是:

([1, 4, 9, 16], 'h', 4)
Run Code Online (Sandbox Code Playgroud)

这是正确的,但如果我这样做:

print(f.fun("April"))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
Run Code Online (Sandbox Code Playgroud)

显然,python 将字符串参数“April”与列表混淆,我该如何解决?

np8*_*np8 5

默认情况下,传递给函数的第一个参数将分配给第一个参数。如果要将第一个参数分配给第二个(或 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
Run Code Online (Sandbox Code Playgroud)

参数的类型无关紧要,重要的是您在函数定义中使用的顺序

术语注释

  • 通过参数,我的意思是函数定义中的变量
  • 通过参数,我的意思是传递给函数的实际值。