Physicist
Physicist

Reputation: 3048

how to get the name of a class variable

Suppose I have the following codes:

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????

I want to write the last line such that I can add the name of the class variable ('lensA') to the list self.__component_name, but not the location of the instance (which is done in self.__component_class). How to do that?

Upvotes: 0

Views: 58

Answers (1)

wwii
wwii

Reputation: 23783

You can find it but it may not be practical and this may not work depending on the scope where it is executed. It seems like a hack and not the correct way to solve the problem.

# 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
>>> 

Upvotes: 2

Related Questions