使字符串成为实例/对象的名称

0 python string variables object

我已经挣扎了几天了以下......

我正在尝试找到一种方法来实例化一些我可以通过raw_input调用命名的对象,然后,当我需要时,通过'print VARIABLE NAME'命令结合str()来查看它的属性方法.

所以,举个例子.假设我想创建一个10只动物的动物园......

    class Zoo(object): 
        def __init__(self, species, legs, stomachs):
            self.species = species
            self.legs = legs
            self.stomachs = stomachs


for i in range(9): 
    species = raw_input("Enter species name: ")
    legs = input("How many legs does this species have? ")
    stomachs = input("...and how many stomachs? ")
    species = Zoo(species, legs, stomachs)
Run Code Online (Sandbox Code Playgroud)

这个想法是'species'变量(for循环的第一行)例如species = Bear成为对象'Bear'(循环的最后一行),它与str()方法和'print Bear'命令一起使用会给我熊的属性.

就像我说的那样,我已经挣扎了一段时间但是尽管看了类似主题的其他帖子仍然无法找到方法.有人说使用字典,其他人说使用setattr(),但我看不出这在我的例子中是如何工作的.

rco*_*der 6

如果您只想在模块命名空间中引入新的命名变量,那么setattr可能是最简单的方法:

import sys

class Species:
    def __init__(self, name, legs, stomachs):
        self.name = name
        self.legs = legs
        self.stomachs = stomachs

def create_species():
    name = raw_input('Enter species name: ')
    legs = input('How many legs? ')
    stomachs = input('How many stomachs? ')
    species = Species(name, legs, stomachs)
    setattr(sys.modules[Species.__module__], name, species)

if __name__ == '__main__':
    for i in range(5):
        create_species()
Run Code Online (Sandbox Code Playgroud)

如果将此代码保存到名为的文件zoo.py,然后从另一个模块导入,则可以按如下方式使用它:

import zoo
zoo.create_species() # => enter "Bear" as species name when prompted
animal = zoo.Bear # <= this object will be an instance of the Species class
Run Code Online (Sandbox Code Playgroud)

但是,通常,使用字典是一种更"Pythonic"的方式来维护命名值的集合.动态绑定新变量有许多问题,包括大多数人都希望模块变量在程序运行之间保持相当稳定的事实.此外,对于Python的变量的命名规则是比可能集合动物名称的更严格的-你不能包含空格的变量名,例如,因此,虽然setattr会很乐意存储的价值,你必须使用getattr到检索它.