在Python中使用变量作为类名? [英] Using Variables for Class Names in Python?

查看:741
本文介绍了在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()

第一行使变量classNameMyClass相同.然后,下一行通过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中,listlist类的构造函数.)

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆