可以用变量来调用函数吗

发布于 2025-01-10 06:06:08 字数 636 浏览 4 评论 0原文

我有四个子例程来对 2 个数字进行乘法、除法、加法和减法,我将向用户询问。

我未完成的代码是:

def multiply(a, b):
    print(f"{a} x {b} = {a*b}")
    
def divide(a, b):
    print(f"{a} ÷ {b} = {a*b}")

num1 = int(input("What is the first number?\n"))
num2 = int(input("What is the second number?\n"))
calculation = input("What calculation would you like to perform? [multiply, divide]\n")

calculation(num1, num2)

但它给出了 TypeError: 'str' object is not callable

是否有必要使用 if 语句,例如:

if calculation == 'multiply':
     multiply()
elif calculation == 'divide':
     divide()

对于所有四个子例程,或者我可以使用变量计算来替换函数名称。

I have four subroutines to multiply, divide, add and subtract 2 numbers which I will ask the user for.

My unfinished code is:

def multiply(a, b):
    print(f"{a} x {b} = {a*b}")
    
def divide(a, b):
    print(f"{a} ÷ {b} = {a*b}")

num1 = int(input("What is the first number?\n"))
num2 = int(input("What is the second number?\n"))
calculation = input("What calculation would you like to perform? [multiply, divide]\n")

calculation(num1, num2)

but it gives TypeError: 'str' object is not callable

Is it necessary to use if statements like:

if calculation == 'multiply':
     multiply()
elif calculation == 'divide':
     divide()

for all four subroutines or can I use the variable calculation to substitute for the function name.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奢望 2025-01-17 06:06:08

使用字典来保存您的函数

funcs = {'multiply': multiply, 'divide': divide}

,然后访问funcs[calculation]

...或者如果您有 DRY 迷恋:

funcs = {f.__name__: f for f in [multiply, divide]}

演示:

>>> funcs['multiply'](3, 4)
3 x 4 = 12

您还可以访问 globals() 字典,

>>> globals()['multiply'](3, 4)
3 x 4 = 12

但这不是一个好主意,因为要调用的函数来自用户输入,谁知道是什么奇怪的可调用对象位于 globals() 中。


奖励:防止错误输入

from functools import partial
def notfound(fname, *_, **__):
    print(f'function {fname!r} not found')

用法:

>>> calculation = 'multiply'
>>> funcs.get(calculation, partial(notfound, calculation))(3, 4)
3 x 4 = 12
>>> calculation = 'none'
>>> funcs.get(calculation, partial(notfound, calculation))(3, 4)
function 'none' not found

Use a dictionary to hold your functions

funcs = {'multiply': multiply, 'divide': divide}

and then access funcs[calculation].

... or if you have a DRY fetish:

funcs = {f.__name__: f for f in [multiply, divide]}

Demo:

>>> funcs['multiply'](3, 4)
3 x 4 = 12

You could also access the globals() dict

>>> globals()['multiply'](3, 4)
3 x 4 = 12

but this is not such a good idea because the function to call comes from user input and who knows what weird callables are in globals().


Bonus: safeguarding against bad input

from functools import partial
def notfound(fname, *_, **__):
    print(f'function {fname!r} not found')

Usage:

>>> calculation = 'multiply'
>>> funcs.get(calculation, partial(notfound, calculation))(3, 4)
3 x 4 = 12
>>> calculation = 'none'
>>> funcs.get(calculation, partial(notfound, calculation))(3, 4)
function 'none' not found
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文