断言是什么意思?它是如何使用的?


当前回答

在Pycharm中,如果你使用assert和isinstance来声明对象的类型,它会让你在编码时访问父对象的方法和属性,它会自动完成。

例如,self。object1。object2是MyClass对象。

import MyClasss

def code_it(self):
    testObject = self.object1.object2 # at this point, program doesn't know that testObject  is a MyClass object yet
    assert isinstance(testObject , MyClasss) # now the program knows testObject is a MyClass object
    testObject.do_it() # from this point on, PyCharm will be able to auto-complete when you are working on testObject

其他回答

def getUser(self, id, Email):

    user_key = id and id or Email

    assert user_key

可用于确保在函数调用中传递参数。

>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)

>>> #first we try without assert
>>>if test_us == True:
    print("YES! I am right!")
else:
    print("I am Wrong, but the program still RUNS!")

I am Wrong, but the program still RUNS!


>>> #now we try with assert
>>> assert test_us
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    assert test_us
AssertionError
>>> 

assert语句有两种形式。

简单形式assert <expression>相当于

if __​debug__:
    if not <expression>: raise AssertionError

扩展形式assert <expression1>, <expression2>等价于

if __​debug__:
    if not <expression1>: raise AssertionError(<expression2>)

如果assert关键字后面的代码为False, Python中的assert关键字将引发AssertionError。如果没有,它继续什么都没有发生。

示例1:

a = 5
b = 6

assert a == b

输出:

AssertionError

这是因为,很明显,a不等于b。 如果你想在代码中引发一个异常,这是特别有用的。

def get_dict_key(d, k):
    try:
        assert k in d
        return d[k]
    except Exception:
        print("Key must be in dict.")

上面的示例实际上是无用的,但是请记住,它主要用于调试目的,因此您可以跟踪错误。

注意括号。正如在其他回答中指出的那样,在Python 3中,assert仍然是一个语句,因此通过与print(..)类比,可以推断出assert(..)或raise(..),但不应该这样做。

这是错误的:

assert(2 + 2 == 5, "Houston we've got a problem")

这是正确的:

assert 2 + 2 == 5, "Houston we've got a problem"

第一个不能工作的原因是bool((False,“Houston we've got a problem”))的值为True。

在assert(False)语句中,这些只是在False周围的多余圆括号,对其内容求值。但是使用assert(False),圆括号现在是一个元组,而非空元组在布尔上下文中的计算结果为True。