Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the type of a class without instantiating it in Python?

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.

like image 389
Regis May Avatar asked Jul 29 '16 11:07

Regis May


People also ask

How to specify a class rather than an instance in Python?

Python Type Hints - How to Specify a Class Rather Than an Instance Thereof 2021-05-16 In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type. To specify that a variable instead contains a type, we need to use type [Cls] (or the old syntax typing.Type).

How does Python instantiate a class?

You trigger Python’s instantiation process whenever you call a Python class to create a new instance. This process runs through two separate steps, which you can describe as follows: Initialize the new instance with an appropriate initial state

What is a class in Python?

Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. To create a class, use the keyword class: The examples above are classes and objects in their simplest form, and are not really useful in real life applications.

How do you create a new class in Python?

In the first line of .__new__ (), you call the parent class’s .__new__ () method to create a new instance and allocate memory for it. To access the parent class’s .__new__ () method, you use the super () function. This chain of calls takes you up to object.__new__ (), which is the base implementation of .__new__ () for all Python classes.


1 Answers

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.

like image 173
jbndlr Avatar answered Oct 04 '22 06:10

jbndlr