我正在尝试运行我的类中的所有函数,而不是单独键入它们。
class Foo(object):
def __init__(self,a,b):
self.a = a
self.b=b
def bar(self):
print self.a
def foobar(self):
print self.b我想要这样做,但是使用一个循环,因为我的实际类大约有8-10个函数。
x = Foo('hi','bye')
x.bar()
x.foobar()发布于 2016-05-06 23:10:04
您可以使用dir()或__dict__遍历对象的所有属性。您可以使用isinstance()和types.FunctionType来区分哪些是函数。只需调用任何属于函数的函数。
更新
正如Tadhg评论的那样,inspect.ismethod似乎是最好的选择。下面是一些示例代码:
import inspect
from itertools import ifilter
class Foo(object):
def foo1(self):
print('foo1')
def foo2(self):
print('foo2')
def foo3(self, required_arg):
print('foo3({!r})'.format(required_arg))
f = Foo()
attrs = (getattr(f, name) for name in dir(f))
methods = ifilter(inspect.ismethod, attrs)
for method in methods:
try:
method()
except TypeError:
# Can't handle methods with required arguments.
pass发布于 2018-09-24 17:33:53
这是解决这个问题的最简单的方法,而且在其中进行更改也是一种灵活的方式。
import threading
from threading import Thread
class ClassName():
def func1(self):
print ('2')
def func2(self):
print ('3')
def runall(self):
if __name__ == '__main__':
Thread(target = self.func1).start()
Thread(target = self.func2).start()
run = ClassName()
run.runall() # will run all the def's in the same time发布于 2016-05-06 23:09:59
您可以获取实例的所有'public‘方法的列表:
x = Foo('hi','bye')
public_method_names = [method for method in dir(x) if callable(getattr(x, method)) if not method.startswith('_')] # 'private' methods start from _
for method in public_method_names:
getattr(x, method)() # call了解更多关于getattr的信息实际上,Python语言没有public或private语义,如果你感兴趣,可以阅读that
https://stackoverflow.com/questions/37075680
复制相似问题