如何将字符串作为对象名称传递?

时间:2019-04-06 06:51:40

标签: python string

这是我最终解决问题的方法:

我创建了两个列表,一个包含对象,另一个包含对象名称(字符串)。然后,我编写代码以确保将对象及其名称同时附加到两个列表中。这样我就可以轻松地使用ObjectList [NameList.index(Name)]调用对象,类似于使用NameList [ObjectList.index(Object)]来调用名称。

我不知道这是否是最好的解决方案。当我对python有更多了解时,也许我会找到一种更好的方法。

感谢大家的帮助。


我在下面更新了我的代码。


我正在尝试制作一款可以吸收用户输入,基于该输入制作新对象并将该对象与现有对象网络连接的游戏。

所以我有初始对象:Adam = Human("Male","God","God")Eve = Human("Female", "God", "God")

但是在AdamEve之后,我想创建类似Josh = Human("Male", Adam, Eve)的对象,这里Josh的属性变成一个字符串和两个对象,而不是三个字符串。但是,如果这样做可行,我可以创建一个对象网络,其中每个对象孩子(亚当和夏娃除外)都有对象父母。

如果有人对此有任何建议,请告诉我。


我想传递用户输入的字符串作为某个类的新对象的名称。我不能使用eval(),因为这很危险。我该怎么办?

我是python3的新手,他创建了一个仅用于练习的小游戏。我创建了一个名为“人类”的类,在游戏中,用户应该输入一个新人类的名称。

我没有尝试太多,因为我发现的所有问题都不符合我的问题。我到目前为止只知道我不能使用eval(),因为如果发生eval("import")之类的事情,可能会引起麻烦。

import random

# list of all humans
Humans = []

# creating the class Human
class Human:

    global Humans

    def __init__(self, gender, father, mother):
        self.gender = gender
        self.father = father
        self.mother = mother
        self.canHaveChild = False
        Humans.append(self)

    def growup(self):
        self.canHaveChild = True


Adam = Human("Male", "God", "God")
Eve = Human("Female", "God", "God")
Humans.append(Adam)
Humans.append(Eve)

# creating the class SpiritualHuman
class SpiritualHuman:

    def __init__(self, gend, stparent, ndparent):
        self.stparent = stparent
        self.ndparent = ndparent
        self.gend = gend
        self.canHaveChild = False

# haveChild function
def haveChild(Human1, Human2):

    gender = ""
    gen_pro = random.random()
    if gen_pro < 0.5:
        gender = "Female"
    else:
        gender = "Male"

    if Human1.canHaveChild & Human2.canHavechild:
        if (Human1.gender == "Male") & (Human2.gender == "Female"):
            return Human(gender, Human1, Human2)
        elif (Human1.gender == "Female") & (Human2.gender == "Male"):
            return Human(gender, Human1, Human2)
        elif (Human1.gender == "Male") & (Human2.gender == "Male"):
            return SpiritualHuman("Yang", Human1, Human2)
        else:
            return SpiritualHuman("Yin", Human1, Human2)
    else:
        return "forbidden child"


# a list of all commands
command_list = ["who is the mother of", "who is the father of", "who is the child of", "have child named"]
# user input could be:
# "who is the mother of xxx"
# "who is the father of xxx"
# "who is the child of xxx and xxx"
# "xxx and xxx have child named xxx"



# user input function
def get_input():
    command = input(":")
    comsplit = command.split()
    # check 1st command
    if command_list[0] in command:
        if comsplit[5] in str(Humans):
            print("the mother of", comsplit[5], "is", Humans[str(Humans).index(comsplit[5])].mother())
        else:
            print(comsplit[5], "does not exist")
    # check 2nd command
    elif command_list[1] in command:
        if comsplit[5] in str(Humans):
            print("the father of", comsplit[5], "is", Humans[str(Humans).index(comsplit[5])].father())
        else:
            print(comsplit[5], "does not exist")
    # check 3rd command
    elif command_list[2] in command:
        if comsplit[5] in str(Humans) and comsplit[7] in str(Humans):
            for i in Humans:
                if str(i.father()) in [comsplit[5], comsplit[7]] and str(i.mother()) in [comsplit[5], comsplit[7]]:
                    print(i, "is the child of", comsplit[5], "and", comsplit[7])
                else:
                    print("they don't have a child")
        else:
            print("at least one of the parents you mentioned does not exist")
    # check 4th command
    elif command_list[3] in command:
        if comsplit[0] in str(Humans) and comsplit[2] in str(Humans):
            # here's where the problem is
            # I want to use comsplit[7] as name for a new Human object
            # how should I do it?

        else:
            print("at least one of them is not human")
    elif command == "humans":
        print(str(Humans))
    else:
        print("invalid command. If you need help, please type 'help'")


while(True):
    get_input()

我不知道如何避免错误,但是我希望用户输入以下内容: Adam and Eve have child named Josh 结果应该是乔希是人类类的对象,其父亲是亚当,母亲是夏娃。

2 个答案:

答案 0 :(得分:2)

使用包含您的人类的字典,将人类的名字作为键:

# global dict, defined at the top of your code
humans = {}

def get_input():
    command = input(":").split()
    if len(command) == 1:
        print(HUMANS) # well, don't know what this one is supposed to be...
    elif len(command) > 1:
        humans[command[1]] = Human(command[1])
        humans[command[2]] = Human(command[2])
        humans[command[0]] = haveChild(humans[command[1]], humans[command[2]])

编辑:我刚刚阅读了您的评论,暂时无法完成回答,但是,简而言之,您必须先以人类的身份创建父母,然后才能使用它们,因此您需要以创建方式进行更改他们...

答案 1 :(得分:1)

用户将输入两个具有其属性(性别,父亲,母亲)的人类对象。这两个对象将传递给<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test</title> <link rel="stylesheet" href="styles/grid.css"> <link rel="stylesheet" href="styles/normalize.css"> </head> <body> <main> <div class="grid__container"> <div class="grid__item__1"> <img src="https://via.placeholder.com/600x150.png/b3dfbe"> </div> <div class="grid__item__2"> <img src="https://via.placeholder.com/600x150.png/75c5b8"> </div> <div class="grid__item__3"> <img src="https://via.placeholder.com/600x320.png/f16789"> </div> <div class="grid__item__4"> <img src="https://via.placeholder.com/200x165.png/8d96f3"> </div> <div class="grid__item__5"> <img src="https://via.placeholder.com/200x165.png/8d96f3"> </div> <div class="grid__item__6"> <img src="https://via.placeholder.com/200x165.png/8d96f3"> </div> <div class="grid__item__7"> <img src="https://via.placeholder.com/300x150.png/fac460"> </div> <div class="grid__item__8"> <img src="https://via.placeholder.com/300x150.png/fac460"> </div> <div class="grid__item__9"> <img src="https://via.placeholder.com/400x185.png/608cc9"> </div> <div class="grid__item__10"> <img src="https://via.placeholder.com/400x185.png/608cc9"> </div> <div class="grid__item__11"> <img src="https://via.placeholder.com/200x195.png/608cc9"> </div> <div class="grid__item__12"> <img src="https://via.placeholder.com/200x195.png/608cc9"> </div> <div class="grid__item__13"> <img src="https://via.placeholder.com/200x145.png/6653af"> </div> <div class="grid__item__14"> <img src="https://via.placeholder.com/600x135.png/6653af"> </div> <div class="grid__item__15"> <img src="https://via.placeholder.com/400x135.png/6653af"> </div> </div> </main> </body> </html>。检查我的代码

haveChild()