我正在尝试获取一个属性来打印它在python的所有者类中分配的名称,并且我已经制定了一种方法,当且仅当直接分配该属性时该方法才有效。如果属性是继承的,它就不起作用,如下图所示。有什么好方法可以在您调用任何一个Handler.CLIENT_ID
或始终打印SubHandler.CLIENT_ID
变量名时?CLIENT_ID
class Auto(object):
def __get__(self, instance, owner):
attr_name = (k for (k, v) in owner.__dict__.iteritems() if v == self).next()
return attr_name
class Handler(object):
name = 'account'
CLIENT_ID = Auto()
class SubHandler(Handler):
pass
h = Handler()
print h.CLIENT_ID
# prints CLIENT_ID
s = SubHandler()
print s.CLIENT_ID
# Traceback (most recent call last):
# attr_name = (k for (k, v) in owner.__dict__.iteritems() if v == self).next()
# StopIteration