웹사이트 검색

파이썬 같지 않은 연산자


Python 같지 않음 연산자는 두 변수가 동일한 유형이고 값이 다른 경우 True를 반환하고, 값이 동일한 경우 False를 반환합니다. Python은 동적이며 강력한 형식의 언어이므로 두 변수의 값이 같지만 형식이 다른 경우 같지 않음 연산자는 True를 반환합니다.

파이썬 같지 않은 연산자

Operator Description
!= Not Equal operator, works in both Python 2 and Python 3.
<> Not equal operator in Python 2, deprecated in Python 3.

파이썬 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
>>> 

파이썬 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
>>> 
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

Python이 사용자 정의 객체와 같지 않음

같지 않음 연산자를 사용하면 __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):
        # return true if different types
        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 리포지토리에서 전체 Python 스크립트와 더 많은 Python 예제를 확인할 수 있습니다.