lundi 29 mars 2021

In Python, how to instantiate a class by its name instead of referencing it directly? [duplicate]

In order to avoid a circular reference, I'd like to reference a class by it's name instead of directly.

For example:

class A:
    x: str = 'nice'

# how can I get this reference by using the name and package of A instead of referencing it directly?
myclass = A

a1 = myclass()

# a1 is an instance of A as expected

print(a1)
>>> <__main__.A object at 0x7f82b86b6eb0>

I'm looking for something like get_class('A') which returns a reference to A. I'm on Python 3.8.5

I'm a new to Python reflection - is there a built in way to do this?

Thanks!





Aucun commentaire:

Enregistrer un commentaire