Convert string to Python class object?
Warning:
eval()
can be used to execute arbitrary Python code. You should never useeval()
with untrusted strings. (See Security of Python's eval() on untrusted strings?)
This seems simplest.
>>> class Foo(object):
... pass
...
>>> eval("Foo")
<class '__main__.Foo'>
Convert type string object to type class object in python
I found a solution. I have made a list of all enemy's along side their name. Then I return the index of the corresponding value to the enemies name. Below is what I came up with.
Enemy creation:
boss = EnemyCreator('Charles Hammerdick', 'boss', 10000, 200)
npc_list.append(boss)
npc_list.append(boss.name)
attack function:
def attack(enemy):
for thing in npc_list:
if str(enemy) in str(thing):
enemy = (npc_list[npc_list.index(thing) - 1])
enemy.health = enemy.health - playerChar.ap
if enemy.health > 0:
playerChar.health = playerChar.health - enemy.ap
return ('You attacked ' + enemy.name + '. ' + str(enemy.health) + ' life remaining. \n'
+ enemy.name + ' attacks back! You take ' + str(enemy.ap) + ' damage. You have ' + str(playerChar.health)
+ ' remaining!')
if enemy.health <= 0:
return enemy.name + ' has been defeated!'
if playerChar.health <= 0:
return 'You died idiot.'
python: Convert string to class object
You need the function getattr
for this:
getattr(temp_text, 'a')
String to Object in Python
You are looking at ways of serialising objects; this is a very standard problem. pickle
is the standard solution, and you should look into it first. If you want to make a class pickleable, you need to define some custom methods on it, and ensure the module in which it is defined can be found on both the source and destination computers. Then you can pickle.dumps(obj)
which will return a string, and pickle.loads(my_str)
to rebuild the object.
Other options include marshal
(low-level) and json
(standard for web data).
How do I convert string to object type without using eval() in for loop?
Store the objects in a dict from their "name" to the instances (it's better to explicitly maintain such a mapping instead of falling to the trap of using locals()
or globals()
).
A = Testclass()
B = Testclass()
objects = {"A": A, "B": B}
seq = ["AB", "BA", "AB"]
for val in seq:
obj1, obj2 = list(val)
objects[obj1].change(objects[obj2])
BTW, it's possible to unpack a string directly without list
:
ob1, obj2 = val
How to convert string to class sub-attribute with Python
The operator.attrgetter
function does this:
class Foo: pass
f = Foo()
f.bar = Foo()
f.bar.baz = Foo()
f.bar.baz.quux = "Found me!"
import operator
print operator.attrgetter("bar.baz.quux")(f) # prints "Found me!"
Get python class object from string
You want to use the importlib
module to handle loading of modules like this, then simply use getattr()
to get the classes.
For example, say I have a module, somemodule.py
which contains the class Test
:
import importlib
cls = "somemodule.Test"
module_name, class_name = cls.split(".")
somemodule = importlib.import_module(module_name)
print(getattr(somemodule, class_name))
Gives me:
<class 'somemodule.Test'>
It's trivial to add in things like packages:
cls = "test.somemodule.Test"
module_name, class_name = cls.rsplit(".", 1)
somemodule = importlib.import_module(module_name)
And it will not import a module/package if it's already been imported, so you can happily do this without keeping track of loading modules:
import importlib
TWO_FACTOR_BACKENDS = (
'id.backends.AllowToBeDisabled', # Disable this to enforce Two Factor Authentication
'id.backends.TOTPBackend',
'id.backends.HOTPBackend',
#'id.backends.YubikeyBackend',
#'id.backends.OneTimePadBackend',
#'id.backends.EmailBackend',
)
backends = [getattr(importlib.import_module(mod), cls) for (mod, cls) in (backend.rsplit(".", 1) for backend in TWO_FACTOR_BACKENDS)]
Related Topics
Check If Values of Multiple Columns Are the Same (Python)
How to Read a List of Parquet Files from S3 as a Pandas Dataframe Using Pyarrow
How to Connect to a Remote Windows Machine to Execute Commands Using Python
Convert HTML String to an Image in Python
Python3 Tkinter Set Image Size
Python List - Only Keep Only-Positive or Only-Negative Values
Splitting Strings into Numbers (Python)
Saving Numpy Array to Txt File Row Wise
Python: How to Match Nested Parentheses With Regex
How to Create Multiple Data Frames Using a for Loop in Python
How to Remove a Single Quotes from a List
How to Export a Table Dataframe in Pyspark to Csv
Split Data Directory into Training and Test Directory With Sub Directory Structure Preserved
How to Find the Average of Particular Numbers in a CSV File
How to Convert a List of Dictionaries to Json in Python/Django