Python의 __sub__ 매직 메서드는 두 개의 인수를 받는 함수를 호출하는 데 사용되지만 첫 번째 인수는 두 번째 인수 클래스의 하위 클래스로 해석됩니다. 하위 클래스가 __sub__ 매직 메서드를 구현하지 않으면 예기치 않은 동작이 발생할 수 있습니다.
The __sub__ magic method is used to implement the subtraction operator for objects. It is called when the - operator is used on two objects of the same type. The __sub__ method should return the result of the subtraction operation. For example, if we have a class that represents a complex number, we could define the __sub__ method like this: class ComplexNumber: def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __sub__(self, other): return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary) Now we can use the - operator on two ComplexNumber objects: c1 = ComplexNumber(1, 2) c2 = ComplexNumber(3, 4) c3 = c1 - c2 print(c3) # Prints ComplexNumber(real=-2, imaginary=-2)
매직 메소드란?
Python에서 매직 메서드는 이름을 지정하지 않고 함수를 호출할 수 있는 특수한 유형의 함수입니다. 이는 함수 이름 앞에 앰퍼샌드(&)를 붙여서 수행됩니다.
매직 메서드 목록
Python에서 마법을 수행하는 방법에는 여러 가지가 있습니다. 다음은 몇 가지입니다.
1. 임의 가져오기
2. 가져오기 시간
3. 수학 가져오기 sqrt, pi에서
4. datetime 가져오기 날짜, 시간부터
5. 연산자 가져오기에서 더하기, 빼기, 곱하기, 나누기
6. functools 가져오기 부분에서
7. 컬렉션 가져오기 데크에서