연산자와 관련된 매직 메서드가 너무 많아서 j는 대략 다음 두 가지 범주를 나열합니다. other)
메서드가 음수를 반환하는 경우 self < other를 의미하며, self > other를 의미합니다. __cmp__를 정의하는 것은 강력히 권장되지 않습니다. 대신 __lt__, __eq__ 및 기타 메서드를 별도로 정의하여 비교 기능을 구현하는 것이 가장 좋습니다. __cmp__는 Python3에서 더 이상 사용되지 않습니다.
__eq__(self, other)은 비교 연산자의 동작을 정의합니다. == | __ne__(self, other)은 비교 연산자의 동작을 정의합니다. != |
__lt__(self, other) | 비교 연산자의 동작을 정의합니다 < |
__gt__(self, other) | 비교 연산자의 동작을 정의합니다 > |
__le__(self, other) | 은 비교 연산을 정의합니다. 연산자 <= |
__ge__(self, other) | 의 동작은 비교 연산자 >= |
의 동작을 정의합니다.이해를 돕기 위해 간단한 예를 살펴보세요.
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class Number(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
print('__eq__')
return self.value == other.value
def __ne__(self, other):
print('__ne__')
return self.value != other.value
def __lt__(self, other):
print('__lt__')
return self.value < other.value
def __gt__(self, other):
print('__gt__')
return self.value > other.value
def __le__(self, other):
print('__le__')
return self.value <= other.value
def __ge__(self, other):
print('__ge__')
return self.value >= other.value
if __name__ == '__main__':
num1 = Number(2)
num2 = Number(3)
print('num1 == num2 ? --------> {} \n'.format(num1 == num2))
print('num1 != num2 ? --------> {} \n'.format(num1 == num2))
print('num1 < num2 ? --------> {} \n'.format(num1 < num2))
print('num1 > num2 ? --------> {} \n'.format(num1 > num2))
print('num1 <= num2 ? --------> {} \n'.format(num1 <= num2))
print('num1 >= num2 ? --------> {} \n'.format(num1 >= num2))출력 결과는
__eq__
num1 == num2 ? --------> False
__eq__
num1 != num2 ? --------> False
__lt__
num1 < num2 ? --------> True
__gt__
num1 > num2 ? --------> False
__le__
num1 <= num2 ? --------> True
__ge__
num1 >= num2 ? --------> False
2입니다.| Magic Method | 지침 |
| __add__(self, other) | 덧셈 연산을 구현합니다. |
| __sub__(self, other) | 뺄셈 연산을 구현합니다. |
| __mul__(self, other) | 곱셈 연산을 구현합니다. |
| __floordiv__(self, other) | // 연산자 |
| ___div__(self, other) | / 연산자를 구현합니다. 그 이유는 Python3에서는 나누기가 기본값이기 때문입니다. 진정한 나누기 |
| __truediv__(self, other) | 는 진정한 나누기를 구현합니다. 이 방법은 __future__ 가져오기 나누기 |
| __mod__(self, other) | 에서 % 연산자를 구현하는 경우에만 적용됩니다. 연산 |
| __divmod__(self, other) | divmod() 내장 함수를 구현합니다. |
| __pow__(self, other) | ** 연산을 구현합니다. |
| __lshift__(self , other) | 비트 연산 구현<< |
| __rshift__(self, other) | 비트 연산 구현>> |
| __and__(self, other) | 비트 연산 구현& |
| __or __( self, other) | 비트 연산 구현` |
| __xor__(self, other) | 비트 연산 구현^ |
이 강좌를 시청한 학생들도 학습하고 있습니다.