有没有一种更简单的方法可以根据输入更改函数的工作方式



我有一个函数,我想根据我给它的输入来做/输出不同的东西。我用if else逻辑做了一些有用的东西,但并不优雅,我怀疑可能有一种更短/更优雅的方法来做。我做的None方法上的if else有什么替代方案?

例如

def foo (a=None, b=None, c=None):
if a is None:
raise ValueError("a cannot be None!")
elif all([b is None, c is None]):
x = operations
return x
elif c is None:
x = operations
y = operations
return x, y
elif b is None:
x = operations
z = operations
return x, z
elif all([b is not None, c is not None]):
x = operations
y = operations
z = operations
return x, y, z

这取决于你所说的"更好";以及您在if和elif中试图做的事情,但我自己也不太喜欢您示例中的代码风格。它可能变得难以阅读和维护。

有些语言使这类事情变得容易,但不幸的是Python不是其中之一。然而,我认为有几种方式是";"更好";,这取决于你想做什么。

  1. 很多elifs:
def show_food_description(food):
if food == "apple":
print("It's red and sweet")
elif food == "banana":
print("It's long and yellow")
elif food == "kiwi":
print("It's green and hairy")
else:
print("This food is unknown")

备选方案:

def show_food_description(food):
descriptions = {
"apple": "It's red and sweet",
"banana": "It's long and yellow",
"kiwi": "It's green and hairy"
}
print(descriptions.get(food, "This food is unknown"))
  1. 测试具有多个值的相等性:
food = "apple"
if food == "apple" or food == "banana" or food == "kiwi":
print("It's a fruit!")

备选方案:

food = "apple"
fruits = ["apple", "banana", "kiwi"]
if food in fruits:
print("It's a fruit!")
  1. 执行不同的功能
def add_one(x):
return x + 1
def add_two(x):
return x + 2
def add_three(x):
return x + 3

def perform_operation(x, operation):
if operation == "add_one":
return add_one(x)
if operation == "add_two":
return add_two(x)
if operation == "add_three":
return add_three(x)
else:
raise Exception("Unknown operation")

备选方案:

def add_one(x):
return x + 1
def add_two(x):
return x + 2
def add_three(x):
return x + 3
def unknown_operation(x):
raise Exception("Unknown operation")
def perform_operation(x, operation):
operations = {
"add_one": add_one,
"add_two": add_two,
"add_three": add_three
}
selected_operation = operations.get(operation, unknown_operation)
return selected_operation(x)

还值得一提的是,在Python 3.10中,有一个match语句可用,它类似于其他语言中的switch语句。下面是一个如何使用它的例子:

language = "Python"
match language:
case "C": print("It's C")
case "Python": print("It's Python")
case _: print("It doesn't matter")

如果安装了Python 3.10,则可以使用匹配用例。请参阅PEP 634

老实说,代码的可读性是非常主观的,如果你在python中寻找类似切换用例逻辑的东西,你的代码看起来会像-

def foo (a=None, b=None, c=None):
match a, b, c:
# Add all your cases
case None, None, _:
# Do Your Operations and Return
return
case other:
print("Other Cases")

这是3.10发布的最好的功能之一。希望这对你有帮助。

如果我理解你的问题,你可能会发现新的模式匹配语法是你想要的(需要python >= 3.10,PEP634中的规范,PEP636中的教程(。

def foo(a=None, b=None, c=None):
match a, b, c:
case a_, None, None:
r = 1 * a_
case None, b_, None:
r = 2 * b_
# add more patterns here
case _:
r = None
return r
foo(a=1)  # 1
foo(b=5)  # 10
foo(a=0, b=0)  # None # no pattern for a and b
foo(c=8)  # None # no pattern for c

注意如果使用if/elif/else,也可以实现同样的效果。

def bar(a=None, b=None, c=None):
if a is not None and b is None and c is None:
r = 1 * a
elif a is None and b is not None and c is None:
r = 2 * b
# add more elifs here
else:
r = None
return r

最新更新