一旦我在Python中拥有属于某个类的对象的特定属性,我怎样才能将其名称作为字符串?这个信息是否包含在某个地方?
在下面的示例中,假设我在某个函数中使用a.someval
:如何从该值中将其名称作为字符串someval
获取?
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)
如果我拥有该对象拥有该属性而不仅仅是属性值本身,我可以回到它的名字做类似的事情:
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
我知道我们可以访问这样的方法名称:
print a.setSomeVal.__name__
# setSomeVal
但是可以从属于自身的属性名称,例如:
def present_yourself(you):
print 'My value is', you
print 'and my name is', '< ** YOUR SOLUTION HERE ** >'
编辑回答@Daniel Roseman的评论:
对于某些对象,例如,方法:
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