首页 > 解决方案 > Python 类输入改进

问题描述

在这段代码中,我只是尝试从用户那里获取有关动物营养、呼吸、排泄和生殖的数据。然后,我把这些动物数据类按用户动物类型输入。之后我创建一个文件来保存这些数据。这只是一个提高自己的练习。我的问题是,即使我将营养或其他数据功能放在动物主类中。我必须为输入规范编写另一个营养等功能。有没有其他简单的方法可以做到这一点而无需纠正额外的输入功能。例如,在代码的开头,我试图将这些输入函数放入动物主类或它的子类中。我无法做到这一点。

另外,我想听听您对我的代码的改进建议。

感谢您的时间。

    # all class


class animal:

    def __init__(self, nutrition = "gg", respiratory = "gg", excretory = "gg", reproductive = "gg"):
        self.nutrition = nutrition
        self.respiratory = respiratory
        self.excretory = excretory
        self.reproductive = reproductive


class land(animal):

    def __init__(self, nutrition, respiratory, excretory, reproductive, climate, animal_type):
        super().__init__(nutrition, respiratory, excretory, reproductive)
        self.climate = climate
        self.animal_type = animal_type

    def land_show_info(self):
        return "Animal Type: {}\nNutrition: {}\nRespiratory: {}\nExcretory: {}\nReproductive: {}\nClimate: {}\n".format(
            self.animal_type, self.nutrition, self.respiratory, self.excretory, self.reproductive, self.climate)


class sea(animal):

    def __init__(self, nutrition, respiratory, excretory, reproductive, climate, animal_type):
        super().__init__(nutrition, respiratory, excretory, reproductive)
        self.climate = climate
        self.animal_type = animal_type

    def land_show_info(self):
        return "Animal Type: {}\nNutrition: {}\nRespiratory: {}\nExcretory: {}\nReproductive: {}\nClimate: {}\n".format(
            self.animal_type, self.nutrition, self.respiratory, self.excretory, self.reproductive, self.climate)


class air(animal):

    def __init__(self, nutrition, respiratory, excretory, reproductive, climate, animal_type):
        super().__init__(nutrition, respiratory, excretory, reproductive)
        self.climate = climate
        self.animal_type = animal_type

    def land_show_info(self):
        return "Animal Type: {}\nNutrition: {}\nRespiratory: {}\nExcretory: {}\nReproductive: {}\nClimate: {}\n".format(
            self.animal_type, self.nutrition, self.respiratory, self.excretory, self.reproductive, self.climate)


# all class input function
def nutrition():
    while True:
        nutrition = input("""
        Please Enter Nutrition Type
        1. Carnivorous    --> 'c'
        2. Herbivorous    --> 'h'
        3. Omnivorous     --> 'o'
        4. No Information --> 'n'\n""")
        if nutrition == 'c':
            nutrition = "Carnivorous"
            break
        elif nutrition == 'h':
            nutrition = "Herbivorous"
            break
        elif nutrition == 'o':
            nutrition = "Omnivorous"
            break
        elif nutrition == 'n':
            nutrition = "No Information"
            break
        else:
            print("""!WARNING!
            ...Improper Input Detected...""")
    return nutrition


def respiratory():
    while True:
        respiratory = input("""
        Please Enter Respiratory Type
        1. with Oxygen    --> '+o2'
        2. without Oxygen --> '-o2'
        3. No Information --> 'n'\n""")
        if respiratory == '+o2':
            respiratory = "with Oxygen"
            break
        elif respiratory == '-o2':
            respiratory = "without Oxygen"
            break
        elif respiratory == 'n':
            respiratory = "No Information"
            break
        else:
            print("""!WARNING!
            ...Improper Input Detected...""")
    return respiratory


def excretory():
    while True:
        excretory = input("""
        Please Enter Excretory Type
        1. Ammonia         --> 'a'
        2. Urea           --> 'u'
        3. Uric Acid      --> 'ua'
        4. No Information --> 'n'\n""")
        if excretory == 'a':
            excretory = "Ammonia"
            break
        elif excretory == 'u':
            excretory = "Urea"
            break
        elif excretory == 'ua':
            excretory = "Uric Acid"
            break
        elif excretory == 'n':
            excretory = "No Information"
            break
        else:
            print("""!WARNING!
            ...Improper Input Detected...""")
    return excretory


def reproductive():
    while True:
        reproductive = input("""
        Please Enter Reproductive Type
        1. Sexual         --> 's'
        2. Asexual        --> 'a'
        3. No Information --> 'n'\n""")
        if reproductive == 's':
            reproductive = "Sexual"
            break
        elif reproductive == 'a':
            reproductive = "Asexual"
            break
        elif reproductive == 'n':
            reproductive = "No Information"
            break
        else:
            print("""!WARNING!
            ...Improper Input Detected...""")
    return excretory


def climate():
    while True:
        climate = input("""
        Please Enter Climate Type
        1. Desert         --> 'd'
        2. Forest         --> 'f'
        3. Tundra         --> 't'
        4. Ice Field      --> 'i'
        5. No Information --> 'n'\n""")
        if climate == 'd':
            climate = "Desert"
            break
        elif climate == 'f':
            climate = "Forest"
            break
        elif climate == 't':
            climate = "Tundra"
            break
        elif climate == 'i':
            climate = "No Ice Field"
            break
        elif climate == 'n':
            climate = "No Information"
            break
        else:
            print("""!WARNING!
            ...Improper Input Detected...""")
    return climate


def animal_type():
    while True:
        animal_type = input("""
        Please Enter Animal Type
        1. Land --> 'l'
        2. Sea  --> 's'
        3. Air  --> 'a'\n""")
        if animal_type == 'l':
            animal_type = "Land"
            break
        elif animal_type == 's':
            animal_type = "Sea"
            break
        elif animal_type == 'a':
            animal_type = "Air"
            break
        else:
            print("""!WARNING!
            ...Improper Input Detected...""")
    return animal_type


# input from user
nutrition = nutrition()
respiratory = respiratory()
excretory = excretory()
reproductive = reproductive()
climate = climate()
animal_type = animal_type()

# animal classification
if animal_type == 'Land':
    animal1 = land(nutrition, respiratory, excretory, reproductive, climate, animal_type)
    print(animal1.land_show_info())
elif animal_type == 'Sea':
    animal1 = sea(nutrition, respiratory, excretory, reproductive, climate, animal_type)
    print(animal1.land_show_info())
else:
    animal1 = air(nutrition, respiratory, excretory, reproductive, climate, animal_type)
    print(animal1.land_show_info())

# Is there a better way to check file is there or not by program itself
while True:
    file_ = input("""Is there a file on C:/Users/Gökberk/Desktop/Animal List.txt directory\n(y/n)""")
    if file_ == "y":
        with open("C:/Users/Gökberk/Desktop/Animal List.txt", "a", encoding="utf-8") as file:
            file.write("##############################\n")
            file.write(animal1.land_show_info())
            break
    elif file_ == "n":
        with open("C:/Users/Gökberk/Desktop/Animal List.txt", "w", encoding="utf-8" ) as file:
            file.write("...Welcome to Animal List File...\n")
            file.write("##############################\n")
            file.write(animal1.land_show_info())
        print("File has been created to C:/Users/Gökberk/Desktop/Animal List.txt")
        break
    else:
        print("""!WARNING!
            ...Improper Input Detected...""")

print("Program is Over")

标签: pythonpython-3.xclass

解决方案


我的想法是为每个规范创建字典,因为我在下面共享代码,到一个 info_dict 类,然后在动物主类中创建参数输入函数(如果可能的话)

nutrition = {1: "Carnivorous",
             2: "Herbivorous",
             3: "Omnivorous",
             4: "No Information",
             input_text: """Please Enter Nutrition Type
                            1. Carnivorous
                            2. Herbivorous
                            3. Omnivorous 
                            4. No Information\n"""}

respiratory = {1: "with Oxygen",
               2: "without Oxygen",
               3: "No Information",
               input_text: """Please Enter Respiratory Type
                              1. with Oxygen
                              2. without Oxygen
                              3. No Information\n"""}

推荐阅读