简体   繁体   中英

What's a simple utility function to differentiate between an old-style and a new-style python class or object

What's a simple utility function to differentiate between an old-style and a new-style python class or object?

Are the following correct/complete:

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

If not, then can you provide a solution. If so, is there a nicer way to do the check?

Using the above, I've not had any problems, but I don't have 100% confidence that it will work for all objects supplied as parameters.

How about:

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

Why not just

type(my_class) is type

True for new style classes, False for classic classes

You can support classes with different metaclasses like this (so long as the metaclass is subclassing type)

issublass(type(myclass), type)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM