使用用户输入在另一个Python文件中打印具有属性的Python类对象

2024-06-28 18:59:27 发布

您现在位置: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文件,其中包含根据用户输入创建的实例集合,如下所示:

Objects.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的替代品! 谢谢


Tags: 文件代码用户namefrompyimportself