How do I achieve the effect of the === operator in Python?

北慕城南 提交于 2020-01-11 04:36:06

问题


How do I achieve the effect of the === operator in Python?

For example, I don't want False == 0 to be True.


回答1:


Try variable is False. False is 0 returns False,




回答2:


If you want to check that the value and type are the same use:

x == y and type(x) == type(y)

In Python, explicit type comparisons like this are usually avoided, but because booleans are a subclass of integers it's the only choice here.


x is y compares identity—whether two names refer to the same object in memory. The Python boolean values are singletons so this will work when comparing them, but won't work for most types.




回答3:


You can use the is operator to check for object identity. False is 0 will return False then.




回答4:


Going with the Mathematica definition, here's a small function to do the job. Season delta to taste:

def SameQ(pram1, pram2, delta=0.0000001):
    if type(pram1) == type(pram2):
        if pram1 == pram2:
            return True
        try:
            if abs(pram1 - pram2) <= delta:
                return True
        except Exception:
            pass
    return False


来源:https://stackoverflow.com/questions/6725559/how-do-i-achieve-the-effect-of-the-operator-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!