1

我正在做一个项目,能够发现类中函数的声明顺序将非常有用。基本上,我希望能够保证一个类中的所有函数都按照它们声明的顺序执行。

最终结果是一个网页,其中函数的输出顺序与声明函数的顺序相匹配。该类将从将其定义为网页的通用基类继承。Web 应用程序将动态加载 .py 文件。

4

2 回答 2

4
class Register(object):
    def __init__(self):
        self._funcs = []

    def __call__(self, func):
        self._funcs.append(func)
        return func


class MyClass(object):

     _register = Register()

     @_register
     def method(self, whatever):
         yadda()

     # etc
于 2013-10-11T15:13:06.303 回答
1
from types import MethodType, FunctionType
methodtypes = set((MethodType, FunctionType, classmethod, staticmethod))

def methods_in_order(cls):
    "Given a class or instance, return its methods in the order they were defined."
    methodnames = (n for n in dir(cls) if type(getattr(cls, n)) in methodtypes)
    return sorted((getattr(cls, n) for n in methodnames), 
                  key=lambda f: getattr(f, "__func__", f).func_code.co_firstlineno)

用法:

class Foo(object):
    def a(): pass
    def b(): pass
    def c(): pass

print methods_in_order(Foo)
[<unbound method Foo.a>, <unbound method Foo.b>, <unbound method Foo.c>]

也适用于实例:

print methods_in_order(Foo())

如果在不同的源文件中定义了任何继承的方法,则排序可能不一致(因为排序依赖于每个方法在其自己的源文件中的行号)。这可以通过手动遍历类的方法解析顺序来纠正。这会有点复杂,所以我不会在这里拍摄。

或者,如果您只想要直接在类上定义的那些,这似乎对您描述的应用程序很有用,请尝试:

from types import MethodType, FunctionType
methodtypes = set((MethodType, FunctionType, classmethod, staticmethod))

def methods_in_order(cls):
    "Given a class or instance, return its methods in the order they were defined."
    methodnames = (n for n in (cls.__dict__ if type(cls) is type else type(cls).__dict__)
                   if type(getattr(cls, n)) in methodtypes)
    return sorted((getattr(cls, n) for n in methodnames), 
                  key=lambda f: getattr(f, "__func__", f).func_code.co_firstlineno)

这假定了一个新样式的类。

于 2013-10-11T15:21:46.640 回答