Once I have a specific attribute of an object belonging to some class in Python, how can I get its name as a string? Is this info contained somewhere?
In the following example, suppose I use a.someval
in some function: how can I get its name as a string someval
just from this value?
class OneClass:
def __init__(self):
self.whatIam = 'I am a OneClass instance'
self.whatIdo = 'Nothing really useful'
def setSomeVal(self, val):
self.someval = val
a = OneClass()
a.setSomeVal(13)
If I had the object owning the attribute and not only the attribute value itself, I could go back to its name doing something like:
def present_yourself_knowing_your_owner_object(you, owner):
print 'My value is', you
print 'My name is', owner.__dict__.keys()[owner.__dict__.values().index(you)]
present_yourself_knowing_your_owner_object(a.someval, a)
# My value is 13
# My name is someval
present_yourself_knowing_your_owner_object(a.whatIam, a)
# My value is I am a OneClass instance
# My name is whatIam
And I know we can access a method name like this:
print a.setSomeVal.__name__
# setSomeVal
But would it be possible to have the attribute name just from itself, something like:
def present_yourself(you):
print 'My value is', you
print 'and my name is', '< ** YOUR SOLUTION HERE ** >'
EDIT to answer @Daniel Roseman's comment:
This can be achieved for some objects, e.g. methods:
def present_yourself(you):
print 'My value is', you
print 'and my name is', you.__name__ #'< ** YOUR SOLUTION HERE ;-) ** >'
present_yourself(a.setSomeVal)
# My value is <bound method OneClass.setSomeVal of <__main__.OneClass instance at 0x7f3afe255f38>>
# and my name is setSomeVal