python - How to check a variable is class object or not -


this question has answer here:

assume simple class:

class myclass(object):     pass  . . . m = myclass print type(m) # gets: <type 'classobj'> # if m classobj, how can check variable class object? 

my question is: how can check variable class object?

a simple solution:

if str(type(m)) == "<type 'classobj'>":     # 

but think there @ least 1 classic way check that.

in 2.x, class object can be type (new-style classes) or classobj (classic classes). type type builtin, classobj type not. so, how it? that's types module for.

isinstance(myclass, (types.typetype, types.classtype)) 

in 3.x, don't need worry classic classes, so:

isinstance(myclass, type) 

even if want compare types directly, should never compare any objects str. compare:

>>> class myclassicclass: ...     pass >>> str(type(myclassicclass)) == "<type 'classobj'>" true >>> str("<type 'classobj'>") == "<type 'classobj'>" true 

you can compare objects directly:

>>> type(myclassicclass) == types.classtype true >>> "<type 'classobj'>" == types.classtype false 

(and in incredibly rare cases need compare string representation reason, want repr, not str.)


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -