有没有办法循环并执行Python类中的所有函数? [英] Is there a way to loop through and execute all of the functions in a Python class?
本文介绍了有没有办法循环并执行Python类中的所有函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
class Foo():
function bar():
pass
function foobar():
pass
逐个如下:
x = Foo()
x.bar()
x。 foobar()
有一个内置的方法循环并执行序列中的每个函数它们是写在类中的?
解决方案
否。您可以访问 Foo .__ dict __
,然后依次调用每个值(捕获不可调用成员的错误),但不保留该订单。
for Foo .__ dict __。values():
try:
callable()
TypeError:
pass
这假设没有函数接受参数,
I have
class Foo():
function bar():
pass
function foobar():
pass
Rather than executing each function one by one as follows:
x = Foo()
x.bar()
x.foobar()
is there a built-in way to loop through and execute each function in the sequence in which they are written in the class?
解决方案
No. You can access Foo.__dict__
, and call each value in turn (catching errors for non-callable members), but the order is not preserved.
for callable in Foo.__dict__.values():
try:
callable()
except TypeError:
pass
This assumes none of the functions take parameters, as in your example.
这篇关于有没有办法循环并执行Python类中的所有函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文