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

标签 python python-3.x

我已经查过了this postthis 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/

    相关文章:

    python - Windows 命令行中的 Django 安装

    python - Django 模型 "doesn' t 声明一个显式的 app_label”

    python - 检查用户名是否已存在于数据库中(Python + Pymongo)

    python-3.x - 如何从 Django 模板中的 API 响应转换日期

    python - 为什么 if 语句在 ElementTree 解析中不起作用?

    android - 通过移动数据发送 POST 请求

    python-3.x - OpenCV xfeatures2d_SURF -213 :The function/feature is not implemented

    python - 有没有办法用下划线(或任何其他符号)替换字符串中的单个空格?

    python - 如何部署使用 export_saved_model 保存的 TensorFlow 模型

    python - 将 pandas DataFrame() 拆分为多列的简洁方法