Это то, что я до сих пор:Как получить конкретное название ссылки класса в Python
def get_concrete_name_of_class(klass):
"""Given a class return the concrete name of the class.
klass - The reference to the class we're interested in.
"""
# TODO: How do I check that klass is actually a class?
# even better would be determine if it's old style vs new style
# at the same time and handle things differently below.
# The str of a newstyle class is "<class 'django.forms.CharField'>"
# so we search for the single quotes, and grab everything inside it,
# giving us "django.forms.CharField"
matches = re.search(r"'(.+)'", str(klass))
if matches:
return matches.group(1)
# Old style's classes' str is the concrete class name.
return str(klass)
Так это работает просто отлично, но мне кажется, Обратите внимание, что я не могу просто сделать klass().__class__.__name__
(не могу иметь дело с args и т. д.).
Также, кто-нибудь знает, как выполнить TODO (например, проверьте, является ли klass
классом и является ли его стиль старого стиля новым стилем)?
Любые предложения были бы весьма признательны.
На основе комментариев вот что я закончил с:
def get_concrete_name_of_class(klass):
"""Given a class return the concrete name of the class.
klass - The reference to the class we're interested in.
Raises a `TypeError` if klass is not a class.
"""
if not isinstance(klass, (type, ClassType)):
raise TypeError('The klass argument must be a class. Got type %s; %s' % (type(klass), klass))
return '%s.%s' % (klass.__module__, klass.__name__)
Это надуманное и глупое. Функции 'type' и' issubclass' расскажут вам все, что вы просите. Почему бы не использовать их? –
@ S.Lott: Извините, если вы считаете, что это было надуманно и глупо. И 'type' и' issubclass' не скажут мне полный путь к классу, что было моим главным вопросом. – sdolan
Что значит «полный путь»? –