【问题标题】:Perform an exception for a list of funtions对函数列表执行异常
【发布时间】:2021-03-30 10:17:34
【问题描述】:

大家好(我是 python 新手) 问题:我使用带有按钮的 ipywidgets,我想调用函数列表,有时函数中存在问题(语法,除以零,...),我尝试放一个异常来传递错误并午餐下一个函数,不要工作:(

我在 jupyter 环境中运行,使用 python 3.8.5.final.0 和 pandas 1.1.3 除以 0 语法问题

def lagrange():
a=2
b=3
print('donner la fonction')
print ('Lagrange : a/b=',a/b)



def newton():
a=2
b=0
print('donner Newton')
print ('Newton : a/b=',a/b)

def jacobi():
a=2
b=3
print('donner Newton')
prindt ('Jacobi : a/b=',a/b)

我的意思是 2 个函数中的一些问题(除以 0 和错误的语法)

import ipywidgets as widgets
from IPython.display import display
button1 = widgets.Button(description="Purge",
                    layout=widgets.Layout(width="auto", height="auto"), button_style="success")

button2 = widgets.Button(description="Mise à Jour",
                    layout=widgets.Layout(width="auto", height="auto"), button_style="primary")

widgets.TwoByTwoLayout(top_left=button1, top_right=button2)


def on_button1_clicked(b):
    marchands = [lagrange(),newton(),jacobi()]
    for entry in marchands : 
        try :
            entry
        except :
            print('Oops! ', entry)
        print (entry,' is OK')

def on_button2_clicked(b):
    mabrouk()

button1.on_click(on_button1_clicked)
button2.on_click(on_button2_clicked)

widgets.TwoByTwoLayout(top_left=button1, top_right=button2)

【问题讨论】:

  • 将异常放在函数中或调用它们时

标签: python function exception


【解决方案1】:

你在错误的时间调用你的函数。在

marchands = [lagrange(),newton(),jacobi()]

您执行这 3 个函数,并将它们的输出存储在列表中。

您要做的是存储函数本身:

marchands = [lagrange ,newton ,jacobi]

并在您的 try: ... except: 块中调用它们:

for entry in marchands : 
        try :
            entry()  # note the parenthesis to call the function
        except :
            print('Oops! ', entry.__name__)
        print (entry.__name__,' is OK')

【讨论】:

  • 完美,谢谢:)。还有一个问题:)我有这个'',我怎么只有函数名而不是其他东西:)
  • 可以使用函数的__name__属性。我相应地编辑了答案中的代码。
猜你喜欢
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多