开发者

how to enumerate class method then chain them with itertools.product() in python?

I just learned yesterday from this site that I can:

class Seq(object):
    def __init__(self, seq):
        self.seq = seq
    def __repr__(self):
        return repr(self.seq)
    def __str__(self):
        return str(self.seq)
    def all(self):
        return Seq(self.seq[:])
    def head(self, count):
        return Seq(self.seq[:count])
    def tail(self, count):
        return Seq(self.seq[-count:])
    def odd(self):
        return Seq(self.seq[1::2])
    def even(self):
        return Seq(self.seq[::2])
    def reverse(self):
        return Seq(self.seq[::-1])

>>> s = Seq(range(0, 100))
>>> print s.head(10).odd().even().reverse()
[9, 5, 1]

I want to enumerate possible combination of those sequence method chains inside of class Seq, may sort of:

itertools.product([s.head,s.odd,s.even,s.reverse], repeat=4)    
# may not just limited those 4 functions
  1. how to use the itertools.product() to

    1). generate invoke-able function chains list? just like this:

    foo = s.head().odd().even().reverse()

    2). generate eval()able chain strings then I can store in ascii file or eval() later or for logging purpose?

  2. the head(), tail() may accept parameter, and even(), odd() is not need to, for example, the paremeter of head() and tail() may from lists:

      head_lmt = [10,20,30]
      tail_lmt = [30,40,50]
      foo = s.head().odd().tail().reverse()
                   ^------------------------------------head_lmt  10 or 20 or 30
                                ^-----------------------tail_lmt  30 or 40 or 50
    

If my Q1 is possible, how I can fill those parameter into the invoke-able list and the eval()-able string开发者_开发技巧, a.k.a generate more specific invoke-able list and the eval()-able string?

Thanks!


Note that something like "s.head()" means a method which is "bound" to that specific instance of Seq, that is, "s." Something like "Seq.head()" means a method which is unbound, so one can still pass in different instances of Seq.

From there it simply requires basic functional composition and string concatenation.

def chain_method(from_method, to_method):
    def inner(arg):
        return to_method(from_method(arg))
    return inner

possible_funcs = []
log_strings = []
for possible_combo in itertools.product([Seq.head,Seq.odd,Seq.even,Seq.reverse], repeat=4):
    meta_method = possible_combo[0]
    for method in possible_combo[1:]:
        meta_method = chain_method(meta_method, method)
    log_string = []
    for method in possible_combo:
        log_string.extend(['.', method.__name__, '()'])
    possible_funcs.append(meta_method)
    log_strings.append("".join(log_string))

I'm not sure what you mean by the examples for the additional parameters, though. How do you intend to combine the different parameter values with the different combinations of functions?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜