区分旧样式和新样式python类或obj的简单实用函数是什么

2024-06-16 22:15:11 发布

您现在位置:Python中文网/ 问答频道 /正文

区分旧式和新式python类或对象的简单实用函数是什么?你知道吗

以下内容是否正确/完整:

isNewStyle1 = lambda o: isinstance(hasattr(o, '__class__') and o.__class__ or o, type)
isNewStyle2 = lambda o: hasattr(o, '__class__') and type(o) == o.__class__ or False

如果没有,那么你能提供一个解决方案。如果是这样的话,有没有更好的方法来检查呢?你知道吗

使用上面的方法,我没有遇到任何问题,但是我没有100%的信心它能对作为参数提供的所有对象起作用。你知道吗


Tags: orand对象方法lambda函数typeclass
2条回答

怎么样:

class A: pass

class B(object): pass


def is_new(myclass):
    try: myclass.__class__.__class__
    except AttributeError: return False
    return True

>>> is_new(A)
False
>>> is_new(B)
True
>>> is_new(A())
False
>>> is_new(B())
True
>>> is_new(list())
True

为什么不干脆

type(my_class) is type

True对于新样式类,False对于经典类

您可以像这样支持具有不同元类的类(只要元类是子类化类型)

issublass(type(myclass), type)

相关问题 更多 >