Reputation: 3456
Given an object it is easy to get the object type in python:
obj = SomeClass()
t = type(obj)
How can I do this without first creating an instance of the class?
Background: Once you have the type you easily can create instances of that type. Using this mechanism I want to pass a type to an object which will later create instances of that type. It would be very reasonable not to have to create an object first which will immediately be thrown away again.
Upvotes: 15
Views: 5897
Reputation: 1474
This answer is for anyone who comes to this page wondering, "how can I check the type of a class without instantiating it in Python?"
If you are working with a variable that contains a class, rather than an object, you can check whether it is a certain class using the issubclass()
built-in function.
Building off the previous answer:
>>> class MyClass(object):
... pass
...
>>> c = MyClass
>>> type(c)
<class 'type'>
>>> issubclass(c, MyClass)
True
Upvotes: 3
Reputation: 5210
See this example code:
class MyClass(object):
pass
if __name__ == '__main__':
o1 = MyClass()
c = MyClass
o2 = c()
print(type(o1), type(o2), MyClass)
Defining a class binds it to its name (here: MyClass
), which is nothing else but a reference to that definition. In this example, issuing c = MyClass
just mirrors the class reference to another variable, the contents of the variables c
and MyClass
now are exactly the same. Thus, you can instantiate objects of that class by calling either of them (i.e. MyClass()
or c()
), resulting in the same effect.
Furthermore, testing for the type of an instantiated object results in the exact same class reference. You can even go one step further and do:
o3 = type(o1)()
Which creates a new instance of the class of which o1
is.
Upvotes: 5