2

我有一个类对象 ,具有Task四个属性tdate和。只必须包含一个值,其他三个属性是可选的。我编写了一个 print 方法,如果它们不为空,它将打印字符串:prioritycheckedt

class Task:
    def __init__(self, _t, _date=None, _priority=None, _checked=False):
        self.t = _t
        try:
            self.date = parser.parse(_date, dayfirst=True) if _date else None
        except:
            self.date = None
        self.priority = _priority
        self.checked = _checked

    def print(self):
        print(self.t, end="")
        if self.date:
            print(self.date, end="")
        if self.priority:
            print(self.priority, end="")

...但我想知道是否有办法将其压缩成一行。在 VB.NET 中,您可以执行以下操作:

Console.Writeline(me.t, If(me.date Is Not Nothing, me.date, ""), If(me.priority Is Not Nothing, me.priority, ""))

我尝试在 Python 中执行此操作,如下所示,但它的工作方式不同:

print(self.t, if(self.date, self.date), if(self.priority, self.priority))

有没有一条线的解决方案,或者任何更简洁的方法?

4

3 回答 3

1

您可以使用filterwithNonebooland by that 来避免打印None

def print(self):    
    print(*filter(None, [self.t, self.date, self.priority]))

或者

def print(self):    
    print(*filter(bool, [self.t, self.date, self.priority]))
于 2020-06-17T10:24:14.313 回答
1

您可以创建一个列表,然后检查该列表是否不是None

class Task:
    def __init__(self, _t, _date=None, _priority=None, _checked=False):
        self.t = _t
        try:
            self.date = parser.parse(_date, dayfirst=True) if _date else None
        except:
            self.date = None
        self.priority = _priority
        self.checked = _checked
        self.print_list = [_t, _date, _priority]

    def print(self):
        [print(i, end=' ') for i in self.print_list if i is not None]

t = Task(_t=4, _date=25)
t.print()

每个变量的列表推导is not None

def print(self):
        [print(i, end=' ') for i in self.print_list if i is not None]

也等价:

def print(self): print(*[i for i in self.print_list if i is not None], end="")

甚至可能把两只鸟一石二鸟dict

class Task:
    def __init__(self, _t, _date=None, _priority=None, _checked=False):
        try:
            temp_date = parser.parse(_date, dayfirst=True) if _date else None
        except:    # I suggest making the except capture a more specific case
            temp_date = None
        self.entities = {'t': _t, 'date': temp_date, 'priority': _priority}

    def print(self): print([v for _, v in self.entities.items() if v is not None], end="")

t = Task(_t=4, _date=25)
t.print()
于 2020-06-17T10:27:10.240 回答
0

您可以连接它们并打印,这将处理空值:

def print(self):
    string= self.t + " " + self.date + " " + self.priority
    print(string,end = "")
于 2020-06-17T10:24:34.540 回答