Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Variables for Class Names in Python?

I want to know how to use variables for objects and function names in Python. In PHP, you can do this:

$className = "MyClass";  $newObject = new $className(); 

How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?

like image 268
Sam McAfee Avatar asked Oct 21 '08 21:10

Sam McAfee


People also ask

Can class name be a variable Python?

In the above example, we created the class variable school_name and accessed it using the object and class name. Note: Like regular variables, class variables can store data of any type. We can use Python list, Python tuple, and Python dictionary as a class variable.

How do you use class variables in Python?

Use class_name dot variable_name to access a class variable from a class method in Python. Use instance to access variables outside the class.

How do you define a class variable in Python?

Class variables are declared when a class is being constructed. They are not defined inside any methods of a class. Because a class variable is shared by instances of a class, the Python class owns the variable. As a result, all instances of the class will be able to access that variable.

Can we say class name as variable?

Answer : Yes we can have it.


2 Answers

Assuming that some_module has a class named "class_name":

import some_module klass = getattr(some_module, "class_name") some_object = klass() 

I should note that you should be careful here: turning strings into code can be dangerous if the string came from the user, so you should keep security in mind in this situation. :)

One other method (assuming that we still are using "class_name"):

class_lookup = { 'class_name' : class_name } some_object = class_lookup['class_name']()  #call the object once we've pulled it out of the dict 

The latter method is probably the most secure way of doing this, so it's probably what you should use if at all possible.

like image 60
Jason Baker Avatar answered Sep 27 '22 20:09

Jason Baker


In Python,

className = MyClass newObject = className() 

The first line makes the variable className refer to the same thing as MyClass. Then the next line calls the MyClass constructor through the className variable.

As a concrete example:

>>> className = list >>> newObject = className() >>> newObject [] 

(In Python, list is the constructor for the list class.)

The difference is that in PHP, you represent the name of the class you want to refer to as a string, while in Python you can reference the same class directly. If you must use a string (for example if the name of the class is created dynamically), then you will need to use other techniques.

like image 40
Greg Hewgill Avatar answered Sep 27 '22 19:09

Greg Hewgill