如何在Python中获取类引用的具体名称(例如“module”u name“gt;”)?

如何在Python中获取类引用的具体名称(例如“module”u name“gt;”)?,python,class,Python,Class,这就是我到目前为止所做的: 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 d

这就是我到目前为止所做的:

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.\uuu name.\uuuu
,或者获得完全限定名,
klass.\uu module.+klass.\uu name.\uuu

如何使用
klass.\uu name.\uuu
,或者获得完全限定名,
klass.\uu module.+klass.\uu name.\uuu>你可以这么说

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
你可以说

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
type函数告诉您名称是类还是旧样式还是新样式

>>> type(X)
<type 'classobj'>
>>> type(Y)
<type 'type'>
type函数告诉您名称是类还是旧样式还是新样式

>>> type(X)
<type 'classobj'>
>>> type(Y)
<type 'type'>

这是做作和愚蠢的。
type
issubclass
函数将告诉您所要求的一切。为什么不使用它们呢?@S.Lott:如果你觉得它是做作和愚蠢的,那就很抱歉了。而
type
issubclass
不会告诉我上课的完整路径,这是我的主要问题。你所说的“完整路径”是什么意思?@sdolan:为了避免写一些看似做作的问题,这有助于解释你要做什么。在这种情况下,这背后似乎没有任何意义。提供一些您想知道这一点的原因可以帮助我们解决您真正的问题,而不是胡乱处理晦涩(和无用)的Python琐事。@S.Lott:感谢您对编写更好问题的反馈。我这样做的真正原因是我正在创建一个Django模型字段来存储数据库中的类。在完整路径中,我指的是“django.form.CharField”,而不仅仅是“CharField”。这是做作和愚蠢的。
type
issubclass
函数将告诉您所要求的一切。为什么不使用它们呢?@S.Lott:如果你觉得它是做作和愚蠢的,那就很抱歉了。而
type
issubclass
不会告诉我上课的完整路径,这是我的主要问题。你所说的“完整路径”是什么意思?@sdolan:为了避免写一些看似做作的问题,这有助于解释你要做什么。在这种情况下,这背后似乎没有任何意义。提供一些您想知道这一点的原因可以帮助我们解决您真正的问题,而不是胡乱处理晦涩(和无用)的Python琐事。@S.Lott:感谢您对编写更好问题的反馈。我这样做的真正原因是我正在创建一个Django模型字段来存储数据库中的类。在完整路径中,我指的是“django.form.CharField”,而不仅仅是“CharField”。
>>> issubclass(y.__class__,object)
True
>>> issubclass(x.__class__,object)
False
>>>