0

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?

6
  • Why would you want to do that? Instead you could have a name property as a part of the Lens class and refer to that. Commented Nov 11, 2015 at 23:15
  • 2
    Objects don't intrinsically have names. What should happen if you do table.addcomponent(Lens(...), 10)? Commented Nov 11, 2015 at 23:16
  • 1
    If you say lens_A = lens_B = Lens(), which name is right. Commented Nov 11, 2015 at 23:18
  • 1
    so other than adding an extra property to the class, there are no ways to get the 'words' (which is 'lensA') that I type for the argument 'component' of the method? Commented Nov 11, 2015 at 23:22
  • Exactly. In fact, for most programming languages, the cases where names of things are observable at execution time are exceptional. The general rule is often that (when done according to the binding semantics of the language) name changes don't change the behaviour of the program. Commented Nov 11, 2015 at 23:30

1 Answer 1

2

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 >>> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.