Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Python class object from class name string in the same module

Tags:

python

I have a class

class Foo():     def some_method():         pass 

And another class in the same module:

class Bar():     def some_other_method():         class_name = "Foo"         # Can I access the class Foo above using the string "Foo"? 

I want to be able to access the Foo class using the string "Foo".

I can do this if I'm in another module by using:

from project import foo_module foo_class = getattr(foo_module, "Foo") 

Can I do the same sort of thing in the same module?

The guys in IRC suggested I use a mapping dict that maps string class names to the classes, but I don't want to do that if there's an easier way.

like image 546
Chris McKinnel Avatar asked Jul 31 '13 01:07

Chris McKinnel


People also ask

How do you convert a string to a class object in Python?

Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.

How do I get the class name of an object in Python?

To get the class name of an instance in Python: Use the type() function and __name__ to get the type or class of the Object/Instance. Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.

Can you create an object of a class within the same class Python?

After it is created, you can add it back to the class with Employee. obj1 = obj1 . The reason for the extra step is that normally just can't create an instance of a class inside the class definition. Otherwise, you're calling a class that hasn't been defined yet.

Can an object have the same name as the class?

In Java it is absolutely correct to specify the name of the class and the name of the variable to be exactly the same. The compiler understands the syntax so it knows what part of the program represents the identifier and what part represents the class name.


1 Answers

import sys getattr(sys.modules[__name__], "Foo")  # or   globals()['Foo'] 
like image 108
khachik Avatar answered Sep 29 '22 21:09

khachik