开发者

How to get a class instance name or the right format for eval(class_instance."func1().func2()") in Python?

开发者 https://www.devze.com 2023-03-10 18:00 出处:网络
In the code below I can get the class name via: s.__class__.__name__#Seq but I can not get the intance name \"s\" directly, this will be problem if i use eval() in:

In the code below I can get the class name via:

s.__class__.__name__   #Seq

but I can not get the intance name "s" directly, this will be problem if i use eval() in:

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

And

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

How?

Code

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

EDIT: in order to eval(), I defined the function below that may work.

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)

Or

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?
    retu开发者_如何转开发rn 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]


If you want to filter all instances of class A and then evaluate call func_foo for them then you are also able to use Ignacio code with a small addition:

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

I am sorry if it is duplicate.

EDITED:

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)
0

精彩评论

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

关注公众号