python - Is there a more efficient method to create a Python class object with optional parameters?
问题描述
I'm new to Python and have a suspicion that I may be carrying over old habits from VB.NET.
I'm trying to create a task scheduler that will read an inputted task, together with the optional parameters of "date" and "priority", which are separated by "//". So an input string can look like any of the below:
Do something // 16-6-20 // 1
Do something // 16-6-20
Do something
I've created a class called Task
with four properties, t
, date
, priority
and checked
(the last one is not important for the purposes of the question.) When the user types in an input string, the string is split and trimmed, and a new class object is created. This is the code:
from dateutil import parser
from datetime import datetime
class Task:
def __init__(self, _t, _date=None, _priority=None, _checked=False):
self.t = _t
self.date = _date
self.priority = _priority
self.checked = _checked
while True:
print("Add a new task/event:")
taskstr = input("> ")
info = [x.strip() for x in taskstr.split("//")]
t = ""
date = None
priority = None
if len(info) == 1:
t = info[0]
elif len(info) == 2:
t = info[0]
date = parser.parse(info[1], dayfirst=True)
elif len(info) == 3:
t = info[0]
date = parser.parse(info[1], dayfirst=True)
priority = info[2]
newtask = Task(t, date, priority)
print(newtask.t, newtask.date, newtask.priority)
So my question is simply: is this an efficient method to instantiate a Python object, when I have two optional parameters, or is there a better/more "Pythony" way to do this? Is there a trick that I'm missing? The code works, but I'm not convinced it's the best.
解决方案
Use *args can skip lot of decisions for the variable length of data.
from dateutil import parser
from datetime import datetime
class Task:
def __init__(self, _t, _date=None, _priority=None, _checked=False):
self.t = _t
self.date = parser.parse(_date, dayfirst=True) if _date else None
self.priority = _priority
self.checked = _checked
while True:
print("Add a new task/event:")
try:
taskstr = input("> ")
except:
break
info = [x.strip() for x in taskstr.split("//")]
newtask = Task(*info)
print(newtask.t, newtask.date, newtask.priority)
推荐阅读
- hibernate - org.hibernate.HibernateException:逻辑连接已关闭
- python - 跳过 Django form.is_valid() 并返回 false
- reactjs - ReactJS 添加 SumUp 外部库
- typescript - 打字稿 JSON 路径类型
- excel - 如何在excel中更改日期和时间格式的格式组合
- ubuntu - 如果不允许 IP,则需要 Squid Auth
- java - 无法附加文件发送电子邮件android 11
- php - 带点字符串的正则表达式异常
- javascript - Javascript 无法在我的表单中正常工作
- excel - sumifs 函数在评估的单元格中有多个字符串