Python 如何获取类变量的名称

Python 如何获取类变量的名称,python,string,class,oop,instance,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

假设我有以下代码:

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.\uu component\u name
,而不是实例的位置(在
self.\uu component\u class
中完成)。如何做到这一点?

您可以找到它,但它可能不实用,而且根据执行它的范围,它可能不起作用。这似乎是一种黑客行为,而不是解决问题的正确方法

# 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
>>> 
#locals()可以代替globals()工作
>>>类Foo(对象):
通过
>>>狮子=Foo()
>>>斑马=Foo()
>>>斑马,狮子
(, )
>>>对于globals()中的k,v.items():
如果v英寸(狮子、斑马):
打印“对象:{}-名称:{}”。格式(v,k)
对象:-名称:lion
对象:-名称:斑马
>>> 

为什么要这样做?相反,您可以将name属性作为
Lens
类的一部分并引用它。对象本质上没有名称。如果您执行
table.addcomponent(Lens(…),10)
,会发生什么?如果您说
Lens\u A=Lens\u B=Lens()
,哪个名称是正确的。因此,除了向类添加额外属性外,没有其他方法可以获取我为方法的参数“component”键入的“words”(即“lensA”)?确切地说。事实上,对于大多数编程语言来说,在执行时可以观察到事物名称的情况是例外的。通常的规则是(当根据语言的绑定语义进行更改时),名称更改不会改变程序的行为。