2010-07-19 50 views
1

这是我到目前为止有:如何获得的具体名称在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__) 
+0

这是人为和愚蠢的。 'type'和'issubclass'函数会告诉你所要求的一切。为什么不使用它们? – 2010-07-19 19:12:28

+0

@ S.洛特:对不起,如果你觉得它是人为的和愚蠢的。而'type'和'issubclass'不会告诉我课程的完整路径,这是我的主要问题。 – sdolan 2010-07-19 19:30:01

+0

“完整路径”是什么意思? – 2010-07-19 21:25:19

回答

2

如何只使用klass.__name__,或者得到完全合格的名称,klass.__module__+'.'+klass.__name__

+0

谢谢你,最好的工程。:) – sdolan 2010-07-19 19:18:07

2

你就可以说

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 
+0

+1:感谢oldstyle与newstyle检查。 – sdolan 2010-07-19 19:18:38

1
>>> class X: 
...  pass 
... 
>>> class Y(object): 
...  pass 
... 

类型函数告诉你如果一个名字是一个类和旧式与新风格。

>>> 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 
>>> 
相关问题