Is there a way to loop through and execute all of the functions in a Python class?

后端 未结 6 1560
南方客
南方客 2020-12-09 06:30

I have

class Foo():
    function bar():
        pass

    function foobar():
        pass

Rather than executing each function one by one as

6条回答
  •  心在旅途
    2020-12-09 06:49

    So long as you're only interested in Python 3.x (and from the empty parentheses in your class statement I'll guess you might be), then there is actually a simple way to do this without decorators: Python 3 allows you to provide your own dictionary like object to use while the class is defined.

    The following code is from PEP3115 except for the last couple of lines which I added to print out the methods in order:

    # The custom dictionary
    class member_table(dict):
      def __init__(self):
         self.member_names = []
    
      def __setitem__(self, key, value):
         # if the key is not already defined, add to the
         # list of keys.
         if key not in self:
            self.member_names.append(key)
    
         # Call superclass
         dict.__setitem__(self, key, value)
    
    # The metaclass
    class OrderedClass(type):
    
       # The prepare function
       @classmethod
       def __prepare__(metacls, name, bases): # No keywords in this case
          return member_table()
    
       # The metaclass invocation
       def __new__(cls, name, bases, classdict):
          # Note that we replace the classdict with a regular
          # dict before passing it to the superclass, so that we
          # don't continue to record member names after the class
          # has been created.
          result = type.__new__(cls, name, bases, dict(classdict))
          result.member_names = classdict.member_names
          return result
    
    class MyClass(metaclass=OrderedClass):
      # method1 goes in array element 0
      def method1(self):
         pass
    
      # method2 goes in array element 1
      def method2(self):
         pass
    
    x = MyClass()
    print([name for name in x.member_names if hasattr(getattr(x, name), '__call__')])
    

提交回复
热议问题