在Python中确定变量是一个新式的类?

Dav*_*sen 14 python class python-2.x

我正在使用Python 2.x,我想知道是否有办法判断一个变量是否是一个新式的类?我知道,如果它是一个旧式的课程,我可以做以下事情来找出答案.

import types

class oldclass:
  pass

def test():
  o = oldclass()
  if type(o) is types.InstanceType:
    print 'Is old-style'
  else:
    print 'Is NOT old-style'
Run Code Online (Sandbox Code Playgroud)

但我找不到任何适用于新式课程的东西.我发现了这个问题,但提出的解决方案似乎没有按预期工作,因为简单的值被识别为类.

import inspect

def newclass(object):
  pass

def test():
  n = newclass()
  if inspect.isclass(n):
    print 'Is class'
  else:
    print 'Is NOT class'
  if inspect.isclass(type(n)):
    print 'Is class'
  else:
    print 'Is NOT class'
  if inspect.isclass(type(1)):
    print 'Is class'
  else:
    print 'Is NOT class'
  if isinstance(n, object):
    print 'Is class'
  else:
    print 'Is NOT class'
  if isinstance(1, object):
    print 'Is class'
  else:
    print 'Is NOT class'
Run Code Online (Sandbox Code Playgroud)

那么无论如何要做这样的事情?或者Python中的所有内容都只是一个类,并且没有办法解决这个问题?

Dan*_*ach 7

我想你要问的是:"我可以测试一个类是否在Python代码中被定义为一个新式的类?".技术上简单的类型,比如int 新式的类,但它仍然是可以区分从内建类型Python编写的类.

这是有用的东西,虽然它有点像黑客:

def is_new_style(cls):
    return hasattr(cls, '__class__') \
           and \
           ('__dict__' in dir(cls) or hasattr(cls, '__slots__'))


class new_style(object):
    pass

class old_style():
    pass

print is_new_style(int)
print is_new_style(new_style)
print is_new_style(old_style)
Run Code Online (Sandbox Code Playgroud)

Python 2.6的输出:

False
True
False
Run Code Online (Sandbox Code Playgroud)

这是一种不同的方式:

def is_new_style(cls):
    return str(cls).startswith('<class ')
Run Code Online (Sandbox Code Playgroud)