在课堂上运行所有功能

I a*_*rge 9 python class

我试图在我的课程中运行所有的功能,而不是单独输入它们.

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)

Kar*_*sai 8

这是解决这个问题的最简单方法,而且在其中进行更改也很灵活。

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)


Via*_*kyi 7

您可以获得实例的所有“公共”方法的列表:

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没有publicprivate语义,你可以阅读如果有兴趣


Don*_*kby 5

您可以使用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)

  • 不妨检查任何 [`callable`](https://docs.python.org/2/library/functions.html#callable) 或使用 [`inspect.ismmethod`](https://docs.python .org/2/library/inspect.html#inspect.ismethod) (2认同)
  • 使用 python 3 不再需要 itertools。ifilter 成为过滤器,它在核心库中。 (2认同)