Convert Variable Name to String?

前端 未结 16 1668
生来不讨喜
生来不讨喜 2020-11-28 04:33

I would like to convert a python variable name into the string equivalent as shown. Any ideas how?

var = {}
print ???  # Would like to see \'var\'
something_         


        
16条回答
  •  误落风尘
    2020-11-28 04:49

    as long as it's a variable and not a second class, this here works for me:

    def print_var_name(variable):
     for name in globals():
         if eval(name) == variable:
            print name
    foo = 123
    print_var_name(foo)
    >>>foo
    

    this happens for class members:

    class xyz:
         def __init__(self):
             pass
    member = xyz()
    print_var_name(member)
    >>>member
    

    ans this for classes (as example):

    abc = xyz
    print_var_name(abc)
    >>>abc
    >>>xyz
    

    So for classes it gives you the name AND the properteries

提交回复
热议问题