Это то, что у меня есть до сих пор:
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 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 classes' str is the concrete class name.
return str(klass)
Итак, это работает очень хорошо, но кажется довольно хакерским, чтобы выполнять поиск регулярных выражений в строке класса. Обратите внимание, что я не могу просто сделать klass().__class__.__name__
(не могу иметь дело с args и т.д.).
Кроме того, кто-нибудь знает, как выполнить TODO (проверьте, является ли klass
классом и является ли его стиль oldsyle vs new style)?
Приветствуются любые предложения.
Основываясь на комментариях здесь, в чем я оказался:
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__)
Как просто использовать klass.__name__
, или получить полное имя, klass.__module__+'.'+klass.__name__
?
Вы можете просто сказать
klass.__module__ + "." + klass.__name__
Как определить, является ли что-то старым классом или новым классом, я рекомендую сказать что-то вроде
from types import ClassType # old style class type
if not isinstance(klass, (type, ClassType)):
# not a class
elif isinstance(klass, type):
# new-style class
else:
# old-style class
>>> class X:
... pass
...
>>> class Y( object ):
... pass
...
Функция type сообщает вам, является ли имя классом и стилем старого стиля или новым.
>>> type(X)
<type 'classobj'>
>>> type(Y)
<type 'type'>
Он также сообщает вам, что такое объект.
>>> x= X()
>>> type(x)
<type 'instance'>
>>> y= Y()
>>> type(y)
<class '__main__.Y'>
Вы можете протестировать старый стиль и новый стиль, просто спросив, что это подкласс.
>>> issubclass(y.__class__,object)
True
>>> issubclass(x.__class__,object)
False
>>>
type
иissubclass
вам все, что вы просите. Почему бы не использовать их?type
иissubclass
не скажут мне полный путь к классу, который был моим главным вопросом.