How to find the name of a property from a Python class

 ̄綄美尐妖づ 提交于 2021-01-28 19:30:47

问题


I'm trying to get a property to print the name that it's assigned to in the owner class in python, and I've worked out a method that seems to work if and only if the property is directly assigned. It doesn't work if the property is inherited, as illustrated below. What's a good way so that when you call either Handler.CLIENT_ID or SubHandler.CLIENT_ID the variable name CLIENT_ID is always printed?

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

回答1:


You could traverse the base classes using the __mro__ attribute of the class, looking for the property in each class' __dict__:

class Auto(object):
    def __get__(self, instance, owner):
        attr_name = (k 
            for klass in owner.__mro__
            for (k, v) in klass.__dict__.iteritems() 
            if v == self).next()
        return attr_name

"mro" stands for method resolution order, and is a list of the base classes in the order that python will look for methods and other class-defined attributes. Scanning this list means you'll look up the property across the base classes in the same order Python would use.

Your example code works correctly with the above code:

>>> h = Handler()
>>> print h.CLIENT_ID
CLIENT_ID
>>> s = SubHandler()
>>> print s.CLIENT_ID
CLIENT_ID


来源:https://stackoverflow.com/questions/12654900/how-to-find-the-name-of-a-property-from-a-python-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!