如何获取 class 变量的名称
how to get the name of a class variable
假设我有以下代码:
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????
我想写最后一行,这样我就可以将 class 变量的名称 ('lensA') 添加到列表 self.__component_name
,但不能添加实例的位置(在 self.__component_class
中完成)。怎么做?
你可以找到它,但它可能不实用,并且这可能不起作用,具体取决于它执行的范围。这似乎是一个 hack 而不是解决问题的正确方法。
# 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
>>>
假设我有以下代码:
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????
我想写最后一行,这样我就可以将 class 变量的名称 ('lensA') 添加到列表 self.__component_name
,但不能添加实例的位置(在 self.__component_class
中完成)。怎么做?
你可以找到它,但它可能不实用,并且这可能不起作用,具体取决于它执行的范围。这似乎是一个 hack 而不是解决问题的正确方法。
# 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
>>>