如何获取类变量的名称

时间:2015-11-11 23:13:50

标签: python string class oop instance

假设我有以下代码:

lens_A = Lens(...) # declare an object of type 'Lens' called 'lens_A'
table = Bench() # declare an object 'Bench' called 'table'
table.addcomponent(lens_A, 10) 

addcomponent(self, component, position): # a method inside the class Bench
    self.__component_class.append(component)
    self.__component_position.append(position)
    self.__component_name.append(...) # how to do this????

我想写最后一行,以便我可以将类变量(' lensA')的名称添加到列表self.__component_name,但不是实例的位置(即在self.__component_class完成。怎么做?

1 个答案:

答案 0 :(得分:2)

您可以找到它,但它可能不实用,这可能不起作用,具体取决于执行的范围。这似乎是一个黑客,而不是解决问题的正确方法。

# locals() might work instead of globals()
>>> class Foo(object):
    pass

>>> lion = Foo()
>>> zebra = Foo()
>>> zebra, lion
(<__main__.Foo object at 0x02F82CF0>, <__main__.Foo object at 0x03078FD0>)
>>> for k, v in globals().items():
    if v in (lion, zebra):
        print 'object:{} - name:{}'.format(v, k)


object:<__main__.Foo object at 0x03078FD0> - name:lion
object:<__main__.Foo object at 0x02F82CF0> - name:zebra
>>>