我试图在我的课程中运行所有的功能,而不是单独输入它们.
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
Run Code Online (Sandbox Code Playgroud)
我想这样做但是有一个循环,因为我的实际类有大约8-10个函数.
x = Foo('hi','bye')
x.bar()
x.foobar()
Run Code Online (Sandbox Code Playgroud)
这是解决这个问题的最简单方法,而且在其中进行更改也很灵活。
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
Run Code Online (Sandbox Code Playgroud)
您可以获得实例的所有“公共”方法的列表:
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
Run Code Online (Sandbox Code Playgroud)
查看更多有关GETATTR
事实上,Python没有public或private语义,你可以阅读这如果有兴趣
您可以使用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
Run Code Online (Sandbox Code Playgroud)