在Python中使用变量作为类名? [英] Using Variables for Class Names in Python?
问题描述
我想知道如何在Python中将变量用于对象和函数名称.在PHP中,您可以执行以下操作:
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();
您如何在Python中执行此类操作?还是我完全不了解Python的一些根本区别,如果是,那是什么?
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?
推荐答案
在Python中,
className = MyClass
newObject = className()
第一行使变量className
与MyClass
相同.然后,下一行通过className
变量调用MyClass
构造函数.
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.
作为一个具体示例:
>>> className = list
>>> newObject = className()
>>> newObject
[]
(在Python中,list
是list
类的构造函数.)
(In Python, list
is the constructor for the list
class.)
区别在于,在PHP中,您将要引用的类的名称表示为字符串,而在Python中,您可以直接引用相同的类.如果必须使用字符串(例如,如果类的名称是动态创建的),则将需要使用其他技术.
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.
这篇关于在Python中使用变量作为类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!