Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

python - Is there a logical difference between 'not ==' and '!= (without is)

Is there a substantial difference in Python 3.x between:

for each_line in data_file:
    if each_line.find(":") != -1:
        #placeholder for code
        #more placeholder

and

for each_line in data:
    if not each_line.find(":") == -1:
        #placeholder for code
        #more placeholder

My question isn't particular to the above usage, but is more general or essential - is this syntactical difference working in a different way, even though the result is the same? Is there a logical difference? Are there tasks where one is more appropriate or is this solely a stylistic difference? If this is merely stylistic, which one is considered cleaner by Python programmers?

Also, is the above an opposite instance of asking what the difference is between is and ==? Is the former, like the latter, a difference of object identity and object value equality? What I mean is, in my above example, is the is in using not implicit?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I understand it, functionally they are not entirely the same; if you are comparing against a class, the class could have a member function, __ne__ which is called when using the comparison operator !=, as opposed to __eq__ which is called when using the comparison ==

So, in this instance,
not (a == b) would call __eq__ on a, with b as the argument, then not the result
(a != b) would call __ne__ on a, with b as the argument.

I would use the first method (using !=) for comparison


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...