首页 > 解决方案 > 使用用户输入在另一个 python 文件中打印具有属性的 Python 类对象

问题描述

主要 Python 代码类:main.py

class Dog():
    name = ""
    location = ""
    barks = False
    NotNaughty = False

    def __init__(self, name, **kwargs):
        self.name = name

class Cat():
    name = ""
    location = ""
    isQuiet = False
    lovesmouse = True

    def __init__(self, name, **kwargs):
        self.name = name

我想创建一个 python 文件,其中包含基于用户输入创建的实例集合,如下所示:

对象.py

from main import Dog, Cat

d = Dog("lucy")
d.location = "California"
d.barks = False
d.NotNaughty = True

c = Cat("sweetie")
c.location = "Seattle"
c.isQuiet = False
c.lovesmouse = True

我的代码是通过 CLI 使用的 python 脚本。因此,我正在考虑使用 Python CLI 包(例如 PyInquirer 或 PySimpleGUI)通过提出问题并使用答案来创建 objects.py 文件来获取用户输入,如上所示。(我需要这个 object.py 文件来实现我的代码中的另一个复杂功能)

使用 PyInquirer 的代码 - 在 main.py 中使用此代码:

from __future__ import print_function, unicode_literals
from PyInquirer import prompt, print_json
from pprint import pprint

print('Hi, welcome to Animal World')
questions = [
    {
        'type': 'rawlist',
        'name': 'Element',
        'message': 'What\'s your first Animal?',
        'choices': ['Dog', 'Cat']
    },
    {
        'type': 'input',
        'name': 'name of animal',
        'message': 'What\'s the name?'
    },
    {
        'type': 'input',
        'name': 'location of animal',
        'message': 'What\'s the location?'
    }
]

answers = prompt(questions)
pprint(answers)

我希望格式与上面在 object.py 中显示的完全一样,而不是直接打印答案。我正在寻找有关如何使用用户输入动态创建 objects.py 的输入。任何建议都受到高度赞赏。也欢迎任何 PyInquirer 的替代品!谢谢!

标签: pythondynamiccommand-line-interfacepython-object

解决方案


推荐阅读