길/Python

magic methods

7he8oy 2021. 2. 12. 20:28

 

__add__ for +

__sub__ for - 
__mul__ for * 
__truediv__ for / 
__floordiv__ for // 
__mod__ for % 
__pow__ for ** 
__and__ for & 
__xor__ for ^ 
__or__ for |

 

 

 

모든 methods에는 r+ 연산자가 뒤따른다.

연산자에 r을 붙이면,

연산이 반대로 되는 경우를 뜻하는 것으로 보인다.

 

 

아래는 magic methods의 예시.

class SpecialString:
    def __init__(self, cont):
        self.cont = cont

    def __truediv__(self, other):
        line = "=" * len(other.cont)
        return "\n".join([self.cont, line, other.cont])

spam = SpecialString("spam")
hello = SpecialString("Hello world!")
print(spam / hello)

#spam  
#============
#Hello world!
class BankAccount:
    def __init__(self, balance):
        self.balance = balance
    def __add__(self, other):
        return BankAccount(self.balance + other.balance)

a = BankAccount(1024)
b = BankAccount(42)

result = a + b
print(result.balance) #1066
class NumBox: 
	def __init__(self, num): 
		self.Num = num 
	def __add__(self, num): 
    	self.Num += num 
    def __radd__(self, num): 
    	self.Num += num 
        
        
n = NumBox(100)
120 + n
n.Num #220


300 + n
n.Num #520


# __radd__ 덕분에 number가 왼쪽으로 와도 계산이 되는 것이다.

 

 

또한 비교의 경우도 그에 따른 method들이 있다.

 

__lt__ for < 
__le__ for <= 
__eq__ for == 
__ne__ for != 
__gt__ for > 
__ge__ for >= 

If __ne__ is not implemented, it returns the opposite of __eq__. 
There are no other relationships between the other operators.

class SpecialString:
    def __init__(self, cont):
        self.cont = cont

    def __gt__(self, other):
        for index in range(len(other.cont)+1):
            result = other.cont[:index] + ">" + self.cont
            result += ">" + other.cont[index:]
            print(result)

spam = SpecialString("spam")
eggs = SpecialString("eggs")
spam > eggs

 

 

 

__len__ for len() 
__getitem__ for indexing 
__setitem__ for assigning to indexed values 
__delitem__ for deleting indexed values 
__iter__ for iteration over objects (e.g., in for loops) 
__contains__ for in 

 

import random

class VagueList:
    def __init__(self, cont):
        self.cont = cont

    def __getitem__(self, index):
        return self.cont[index + random.randint(-1, 1)]

    def __len__(self):
        return random.randint(0, len(self.cont)*2)

vague_list = VagueList(["A", "B", "C", "D", "E"])
print(len(vague_list))
print(len(vague_list))
print(vague_list[2])
print(vague_list[2])



그 밖에도  다음과 같은 것들이 있다.

__call__  for calling objects as functions

__int__ for converting objects to buit-in types

__str__ for converting objects to buit-in types