Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在类路径中使用变量名/在引用语句中使用变量?python_Python_Class_Import - Fatal编程技术网

如何在类路径中使用变量名/在引用语句中使用变量?python

如何在类路径中使用变量名/在引用语句中使用变量?python,python,class,import,Python,Class,Import,我希望这已经被很好地涵盖了(如果是的话,我很抱歉),但我在研究中找不到它,因为我不知道该问什么/如何正确表达这个问题。基本上,我想从另一个模块获取对象实例的属性,但我想将该实例作为变量调用。我正在使用Eclipse for Python 因此,在一个模块(与类同名)中,我有如下内容 class Example(object): def __init__(self, name, width, type): self.name = name self.width = width

我希望这已经被很好地涵盖了(如果是的话,我很抱歉),但我在研究中找不到它,因为我不知道该问什么/如何正确表达这个问题。基本上,我想从另一个模块获取对象实例的属性,但我想将该实例作为变量调用。我正在使用Eclipse for Python

因此,在一个模块(与类同名)中,我有如下内容

class Example(object):
def __init__(self, name, width, type):
    self.name = name
    self.width = width
    self.type = type

new_example1= Example('abc', 6, 2)
import Example

name = new_example.name
然后在另一个模块中,我想获得新的名称\u示例1

我可以这样做

class Example(object):
def __init__(self, name, width, type):
    self.name = name
    self.width = width
    self.type = type

new_example1= Example('abc', 6, 2)
import Example

name = new_example.name
但我不想明确地说new_example1-我想使用一个变量

如果我像字符串一样设置变量,那么它就不起作用

variable = 'new_example1'
name = variable.name

我应该如何正确地做到这一点?谢谢

你在旅行中看到过吗?哈哈,没有,我的旅行大约是10天前开始的——在此之前,我从来没有编写过任何程序,更不用说看到一行Python了,所以我仍然对Python提供的很多东西一无所知。很高兴它很简单。谢谢注意:如果变量名具有某种数据结构,则这可能被视为代码气味。这取决于您的用例,但您最好使用dict将名称映射到对象,而不是结构化变量名称。谢谢。我想我需要多读一点关于预定义函数的内容。
import Example
name = getattr(Example, 'new_example1').name