Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

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

I have

class Foo():
    function bar():
        pass

    function foobar():
        pass

Rather than executing each function one by one as follows:

x = Foo()
x.bar()
x.foobar()

is there a built-in way to loop through and execute each function in the sequence in which they are written in the class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
def assignOrder(order):
  @decorator
  def do_assignment(to_func):
    to_func.order = order
    return to_func
  return do_assignment

class Foo():

  @assignOrder(1)
  def bar(self):
    print "bar"

  @assignOrder(2)
  def foo(self):
    print "foo"

  #don't decorate functions you don't want called
  def __init__(self):
    #don't call this one either!
    self.egg = 2

x = Foo()
functions = sorted(
             #get a list of fields that have the order set
             [
               getattr(x, field) for field in dir(x)
               if hasattr(getattr(x, field), "order")
             ],
             #sort them by their order
             key = (lambda field: field.order)
            )
for func in functions:
  func()

That funny @assignOrder(1) line above def bar(self) triggers this to happen:

Foo.bar = assignOrder(1)(Foo.bar)

assignOrder(1) returns a function that takes another function, changes it (adding the field order and setting it to 1) and returns it. This function is then called on the function it decorates (its order field gets thus set); the result replaces the original function.

It's a fancier, more readable and more maintainable way of saying:

  def bar(self):
    print "bar"
  Foo.bar.order = 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...