这是我到目前为止有:如何获得的具体名称在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__
(不能处理参数等)
另外,有没有人知道如何完成TODO(检查klass
是否是一个类,是否旧式vs新款)?
任何建议将不胜感激。
基础上的评论这里是我结束了:
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'函数会告诉你所要求的一切。为什么不使用它们? – 2010-07-19 19:12:28
@ S.洛特:对不起,如果你觉得它是人为的和愚蠢的。而'type'和'issubclass'不会告诉我课程的完整路径,这是我的主要问题。 – sdolan 2010-07-19 19:30:01
“完整路径”是什么意思? – 2010-07-19 21:25:19