python - 使用用户输入在另一个 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 的替代品!谢谢!
解决方案
推荐阅读
- excel - 保留粘贴值的条件格式
- r - 如何计算R中数据框的某些行的总和
- javascript - 为什么我得到 Uncaught TypeError: $(...).DataTable is not a function
- botframework - 如何在安装团队机器人上向组的所有成员发送消息
- sql - HSQLDB 的唯一索引查询
- python - django 数据库没有从我输入的详细信息中保存联系人数据
- r-markdown - 附录中带有 LaTex 文档的 Rmarkdown?
- oop - 在外部库中扩展类
- javascript - 在 useEffect 完成之前组件命中重定向
- symfony - 将属性传递给 Doctrine AbstractIdGenerator