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.
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.
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.
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.
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.
import sys getattr(sys.modules[__name__], "Foo") # or globals()['Foo']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With