1

Is there a way to get the name under which a variable or a property is stored?

Something like:

class X:
  def __init__(self):
    self.name = __name_under_which_I_m_stored__

jeff = X()
print(jeff.name) # yields 'jeff'

Pretty sure that this is not possible, but you never know... Furthermore, I'm aware that the name could be unspecified (do_something(X())) or ambiguous (jeff=frank=X()).

Michael
  • 7,407
  • 8
  • 41
  • 84
  • Do you mean to get the property based on value. For example if self.x = 5, you want to get `x` when `5` is passed? else, provide some example. – Moinuddin Quadri Oct 09 '16 at 18:18

1 Answers1

3

The Python VM has no way to know the literal name of a name. For objects, you can access the name via __name__ attribute.

If you want to do this, you'll need to implement a mapping of names to values. You can do this with a dict.

class X:
  def __init__(self):
    self.names = {};

  def set(self, name, value):
    self.names[name] = value

  def get(self, name):
      return (name, self.names[value])



jeff = X()
jeff.set("name", "jeff");
print(jeff.get("name")) # yields ("name", "jeff")
Ryan
  • 14,392
  • 8
  • 62
  • 102