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 3.6 이상 버전을 사용하는 경우 f-strings와 함께 Python 등호 연산자를 사용할 수도 있습니다.
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)
함수가 호출됩니다. 따라서 우리는 객체에 대한 사용자 정의 구현을 정의하고 자연스러운 출력을 변경할 수 있습니다. 예를 들어, id와 record 필드가 있는 Data
클래스가 있다고 가정해 봅시다. 부등호 연산자를 사용할 때, 우리는 레코드 값만을 비교하고 싶습니다. 우리는 자체 __ne__() 함수를 구현하여 이것을 달성할 수 있습니다.
class Data:
id = 0
record = ''
def __init__(self, i, s):
self.id = i
self.record = s
def __ne__(self, other):
# 다른 유형이면 true를 반환
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