【问题标题】:Filter out boolean as non-integer?将布尔值过滤为非整数?
【发布时间】:2017-01-26 08:50:37
【问题描述】:

我一直想知道下面的代码sn-p:

import math
def func(n):
    if not isinstance(n, int):
        raise TypeError('input is not an integer')
    return math.factorial(n)

print(func(True))
print(func(False))

我总是对结果感到惊讶,因为 TrueFalse 确实有效并且被解释为整数 10。因此,当使用TrueFalse 时,阶乘函数会产生预期的结果11。这些布尔值的行为显然是described in the python manual,并且在大多数情况下,我可以接受布尔值是整数的子类型这一事实。

但是,我想知道:有没有什么聪明的方法可以洗掉像 True 这样的东西作为阶乘函数(或任何其他需要整数的上下文)的实际参数,它会抛出某种程序员能处理的异常?

【问题讨论】:

  • 你不应该依赖python中的严格类型检查。如果想用布尔值调用函数,为什么不呢?
  • @Daniel 我不太清楚为什么它让我有点困扰。在这种特定的情况下,知道阶乘与布尔值配合得很好,这让人感到不满意。我想知道:为什么你更喜欢在 Python 中使用严格的类型检查?

标签: python integer boolean


【解决方案1】:

类型boolint子类型isinstance 可以通过继承传递True 作为int 类型。

使用更严格的type

if type(n) is not int:
    raise TypeError('input is not an integer')

【讨论】:

  • 感谢您的帮助。我完全失明了,因为直到刚才我才意识到 typeisinstance 的细微差别。
【解决方案2】:

这段代码似乎可以区分函数中的布尔参数和整数参数。我错过了什么?

import math
def func(n):
    if type(n) == type(True):
        print "This is a boolean parameter"
    else:
        print "This is not a boolean parameter"
    if not isinstance(n, int):
        raise TypeError('input is not an integer')
    return math.factorial(n)

print(func(True))
print(func(False))
print(func(1))

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 1970-01-01
    • 2013-12-03
    • 2018-10-22
    • 1970-01-01
    • 2017-03-07
    • 2017-06-25
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多