פעולת האופרטור "לא שווה" ב-Python מחזירה True
אם שתי המשתנים הם מאותו סוג ויש להם ערכים שונים, אם הערכים זהים אז היא מחזירה False
. Python היא שפת תכנות דינמית ובעלת סוגים חזקים, כך שאם שני המשתנים יש להם את אותם ערכים אך הם מסוגים שונים, אז אופרטור "לא שווה" יחזיר True
.
אופרטורי "לא שווה" ב-Python
Operator | Description |
---|---|
!= | Not Equal operator, works in both Python 2 and Python 3. |
<> | Not equal operator in Python 2, deprecated in Python 3. |
דוגמה ב-Python 2
בואו נראה כמה דוגמאות לאופרטור "לא שווה" ב-Python 2.7.
$ python2.7
Python 2.7.10 (default, Aug 17 2018, 19:45:58)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 <> 20
True
>>> 10 <> 10
False
>>> 10 != 20
True
>>> 10 != 10
False
>>> '10' != 10
True
>>>
דוגמה ב-Python 3
כאן יש כמה דוגמאות עם מסוף Python 3.
$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 <> 20
File "<stdin>", line 1
10 <> 20
^
SyntaxError: invalid syntax
>>> 10 != 20
True
>>> 10 != 10
False
>>> '10' != 10
True
>>>
ניתן להשתמש באופרטור "לא שווה" ב-Python גם עם f-strings אם אתה משתמש בגרסה 3.6 או גרסה גבוהה יותר.
x = 10
y = 10
z = 20
print(f'x is not equal to y = {x!=y}')
flag = x != z
print(f'x is not equal to z = {flag}')
# python is strongly typed language
s = '10'
print(f'x is not equal to s = {x!=s}')
פלט:
x is not equal to y = False
x is not equal to z = True
x is not equal to s = True
פייתון לא שווה עם אובייקט מותאם אישית
כאשר אנו משתמשים באופרטור לא שווה, זה קורא לפונקציה __ne__(self, other)
. לכן אנו יכולים להגדיר את המימוש המותאם אישית שלנו עבור אובייקט ולשנות את הפלט הטבעי. נניח שיש לנו מחלקת Data
עם שדות – id ו-record. כאשר אנו משתמשים באופרטור לא-שווה, אנו רוצים פשוט להשוות אותו לערך של record. אנו יכולים להשיג זאת על ידי המימוש שלנו של פונקצית __ne__().
class Data:
id = 0
record = ''
def __init__(self, i, s):
self.id = i
self.record = s
def __ne__(self, other):
# יחזיר נכון אם סוגים שונים
if type(other) != type(self):
return True
if self.record != other.record:
return True
else:
return False
d1 = Data(1, 'Java')
d2 = Data(2, 'Java')
d3 = Data(3, 'Python')
print(d1 != d2)
print(d2 != d3)
פלט:
False
True
שים לב שערכי הרשומה של d1 ו-d2 זהים אך "id" שונה. אם נסיר את הפונקציה __ne__(), אז הפלט יהיה כזה:
True
True
באפשרותך לבדוק את התסריט המלא של פייתון ועוד דוגמאות בפייתון מה-מאגר ה-GitHub שלנו.
Source:
https://www.digitalocean.com/community/tutorials/python-not-equal-operator