Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a variable is class object or not [duplicate]

Assume a simple class:

class MyClass(object):
    pass

.
.
.
m = MyClass
print type(m) # gets: <type 'classobj'>
# if m is classobj, how can i check a variable is class object?

My question is: how can i check a variable is a class object?

a simple solution:

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

But i think there is at least one classic way to check that.

like image 741
pylover Avatar asked Apr 05 '13 18:04

pylover


People also ask

How do you check whether a variable is a class or not?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .

How do you check if an object is an instance of a particular class?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

How do you check if a variable is a class type in Python?

Python has a built-in function called type() that helps you find the class type of the variable given as input. Python has a built-in function called isinstance() that compares the value with the type given. If the value and type given matches it will return true otherwise false.


1 Answers

Use inspect:

import inspect
print inspect.isclass(obj)
like image 57
Jochen Ritzel Avatar answered Oct 14 '22 07:10

Jochen Ritzel