PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, September 14, 2022

[FIXED] How to call class constructor having its name in text variable? [Python]

 September 14, 2022     constructor, exec, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing