您可以将检查与orx.__class__
的存在(或不存在)结合起来,作为区分新/旧样式类和用户/内置对象的一种hacky方法。'__dict__' in dir(x)
hasattr(x, '__slots__')
实际上,这个完全相同的建议出现在https://stackoverflow.com/a/2654806/1832154
def is_instance_userdefined_and_newclass(inst):
cls = inst.__class__
if hasattr(cls, '__class__'):
return ('__dict__' in dir(cls) or hasattr(cls, '__slots__'))
return False
>>> class A: pass
...
>>> class B(object): pass
...
>>> a = A()
>>> b = B()
>>> is_instance_userdefined_and_newclass(1)
False
>>> is_instance_userdefined_and_newclass(a)
False
>>> is_instance_userdefined_and_newclass(b)
True