這是我到目前爲止有:如何獲得的具體名稱在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