Python 都没有或都是别的东西

Python 都没有或都是别的东西,python,python-3.x,Python,Python 3.x,我需要一个类的两个属性都是None或者都是int。已经有了一些检查,以确保如果它们都设置为None以外的值,那么它们将是int。因此,在\uuuu init\uuuu方法的末尾,我调用了一个小函数,该函数检查它们的类型是否按任意顺序不同: def both_none_or_both_something_else(a,b): if a is None and b is not None: return False if b is None and a is not

我需要一个类的两个属性都是
None
或者都是
int
。已经有了一些检查,以确保如果它们都设置为None以外的值,那么它们将是int。因此,在
\uuuu init\uuuu
方法的末尾,我调用了一个小函数,该函数检查它们的类型是否按任意顺序不同:

def both_none_or_both_something_else(a,b): 
    if a is None and b is not None:
        return False
    if b is None and a is not None:
        return False
    return True

>> both_none_or_both_something_else(5,None)  # False

>> both_none_or_both_something_else(None,3)  # False

>> both_none_or_both_something_else(5,20)  # True

>> both_none_or_both_something_else(None, None)  # True

这两个变量的检查可以压缩成一行吗?

只需比较
无的测试结果即可:

return (a is None) == (b is None)
只要做:

return type(a) == type(b) and type(a) in [int, type(None)]

这可能不是你要找的,但比任何一行都清楚

def both_none(a,b):
   return a is None and b is None

def both_not_none(a,b):
   return a is not None and b is not None

def both_none_or_both_something_else(a,b): 
   return both_none(a,b) or both_not_none(a,b)

您需要逻辑异或运算符:if different->false,if equal->true

异或(XOR、EOR或EXOR)是一种逻辑运算符,当其中一个操作数为真(一个为真,另一个为假)但两个操作数均为非真且两个操作数均为假时,该运算符的结果为真。在逻辑条件生成中,当两个操作数都为true时,简单的“or”有点不明确

输出:

False
False
True
True
False
False
True
True
备注:

如果两者都是None或都是int:

def both_none_or_both_something_else(a,b):
    return not type(a) != type(b)

print (both_none_or_both_something_else(5,None))
print (both_none_or_both_something_else(None,3))
print (both_none_or_both_something_else(5,20))
print (both_none_or_both_something_else(None,None))
输出:

False
False
True
True
False
False
True
True

你可以这样说

all(x is None for x in (a, b)) or all(x is not None for x in (a,b))
但我不能说这是一种进步。如果您反复需要它,您可以通过将它们封装到谓词中来实现某种优雅:

def all_none(*args):
    return all(x is None for x in args)

def none_none(*args):
    return all(x is not None for x in args)

打印((a和b)或(不是a和b))
@错误语法自责Corrected@Error-语法自责OP到底在哪里声明可以有不同的类型?@Error syntacticalreforme问题是:如果。。。else True
始终是多余的,可以完全忽略,也可以用
bool(…)
not…
替换。使用
bool
构造函数是危险的,因为OP只想测试
None
,而不是所有的假值,其中包括0。这也通过了
(0,无)
(0,5)
返回
False
的测试,这是一个边缘情况,我没有想到某些解决方案可能无法通过。这实际上只是确保
的测试结果对这两个值都是相同的,这正是你想要的。没有比这更复杂或更复杂的了。:)