首页 > 解决方案 > 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.

标签: python

解决方案


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)

推荐阅读