Issue
Let's assume we have some classes defined and available in global namespace. In example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Vector:
def __init__(self, alpha, r):
self.x = r * cos(alpha)
self.y = r * sin(alpha)
# and many others...
How to do this:
class_name = 'Point'
x = 14.361
y = -8.100
code_str = 'class_object = ' + class_name + '(' + str(x) + ', ' + str(y) + ')'
exec code_str # That evaluates to: "class_object = Point(14.361, -8.100)"
print class_object.x, class_object.y
without using the dangerous exec?
PS. I'm intending to load the data from some txt or json file if anyone asks.
Solution
If the class is defined or imported in the same module, you could use something like :
globals()[class_name](x, y)
if you have many classes to handle, you should better use a dictionnary to store them, key is the name, value is the class,
then you can call it with :
my_classes = {'Point' : Point, 'Point2' : Point2}
class_name = 'Point'
x = 14.361
y = -8.100
my_classes[class_name](x, y)
Answered By - PRMoureu Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.