python - 当 'None' 或没有传递参数时,如何接受函数中的默认参数?

标签 python function default-parameters

我正在编写一个具有通用函数的新 python 类。有一次我有如下要求

def function(a=1):
    ....
    ....
    print a # here I want a to be 1 if None or nothing is passed

例如:

  • a(None) 应该打印 1
  • a() 应该打印 1
  • a(2) 应该打印 2

有办法吗?

最佳答案

您可以定义一个带有默认参数的函数,稍后您可以检查传递的值并打印它:

def fun(a=1):
    a = 1 if a is None else a
    print(a)

关于python - 当 'None' 或没有传递参数时,如何接受函数中的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36932281/

相关文章:

python - Python包的本地集合: best way to import them?

python - 我不明白使用 np.boxplot 获得 Q1 和 Q3 的结果

python - 我们什么时候应该在 Python 项目中调用 logging.basicConfig?

function - Lua 只调用存在的函数?

performance - 为什么 PostgreSQL 多次调用我的 STABLE/IMMUTABLE 函数?

c# - 类中的属性/方法占用内存空间吗?

python - "Least Astonishment"和可变默认参数

python - 用于将字典值转换为单独字典的单行

c++ - 构造函数默认参数

C 默认参数