如何在Python中获取eval(class_instance。“func1()。func2()”)的类实例名称或正确格式?

时间:2011-06-07 08:25:41

标签: python parameters eval instance

在下面的代码中,我可以通过以下方式获取课程名称:

s.__class__.__name__   #Seq

但是我无法直接获得intance名称“s”,如果我使用eval(),这将是个问题:

eval(s."head(20).tail(10)")      # must be eval("s.head(20).tail(10)")

def foo(i_cls):
    eval(i_cls."head(20).tail(10)")

如何?

代码

class Seq(object):
        def __init__(self, seq):
            self.seq = seq
            self.name = ""              **#EDIT**
        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:])

s = Seq(range(0, 100))
print s.head(20).tail(10)             # "Method chain" invoking, work as linux command:
                                      #     seq 0 100 | head -20 | tail -10

编辑:为了eval(),我定义了下面可能有效的函数。

def cls_name_eval(i_cls, eval_str, eval_name = "i_cls"):
    i_cls.name = eval_name
    eval_str = i_cls.name + "." + eval_str   #i_cls.head(20).tail(10)
    return i_cls, eval_str

i_cls, eval_str = cls_name_eval(s, "head(20).tail(10)")
eval(eval_str)

或者

def cls_name_eval(i_cls, eval_str, eval_name = "i_cls"):
    i_cls.name = eval_name
    eval_str = i_cls.name + "." + eval_str
    #print i_cls.head(20).tail(10)             #i_cls.head(20).tail(10), will not working, must print?
    return eval(eval_str)

print cls_name_eval(s, "head(20).tail(10)")

v = Seq(range(44, 200))
print cls_name_eval(v, "head(20).tail(10)")


*** Remote Interpreter Reinitialized  ***
>>>
[9, 5, 1]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[54, 55, 56, 57, 58, 59, 60, 61, 62, 63]

1 个答案:

答案 0 :(得分:1)

如果您想过滤A类的所有实例,然后评估call func_foo for them,那么您还可以使用Ignacio代码添加一小部分:

map(lambda inst: getattr(inst, 'func_foo')(), filter(lambda x: isinstance(x, A), locals().values()))

如果重复,我很抱歉。

编辑:

l = locals()
instanceNames = filter(lambda x: isinstance(l[x], Seq), l)# gives you all Seq instances names
map(lambda inst: eval(inst+'.head(20).tail(10)'), filter(lambda x: isinstance(l[x], Seq), l))

OR:

instName = 'tst'
exec('%s = Seq(%s)'% (instName, str(range(100))))
eval('%s.head(20).tail(10)' % variable)