youngfromnowhere
[Python] python의 special methods 본문
Linked list의 node를 구현하려는데 강의에서 다음과 같은 코드를 줬다.
class Node:
def __init__(self, data):
self.data = data
self.next = None
굉장히 마음에 안드는게, python의 built-in function 즉, 예약어인 next를
객체변수의 변수명으로 썼기 때문이다.
클래스 안에 __next__ method를 정의하면
해당 클래스의 객체에 next() function을 쓸 수 있게 된다.
class Node:
def __init__(self, data):
self.data = data
self.next_node = None
def __next__(self):
return self.next_node
다음 노드를 가리키는 참조변수의 이름은 next와 겹치지 않게 next_node로 했다.
self.__next__가 self.next_node를 반환하도록 하면,
node_0 = Node(3) #Value3을 가진 node 생성
node_1 = Node(8) #Value8을 가진 node 생성
node_0.next_node = node_1
print(id(next(node_0)) == id(node_1)) #True
next(node_0)가 node_0의 다음 node를 반환한다.
next()는 인자로 전달받은 객체의 __next__ method를 호출하기 때문이다.
이렇게 Class를 정의할 때 여러 special method들을 overload하면
내가 정의한 Class의 객체들에 built-in function이나 operator가 작용하도록
만들 수 있다.
https://www.pythonlikeyoumeanit.com/Module4_OOP/Special_Methods.html
Special Methods — Python Like You Mean It
Special Methods In this section, we will learn about a variety of instance methods that are reserved by Python, which affect an object’s high level behavior and its interactions with operators. These are known as special methods. __init__ is an example o
www.pythonlikeyoumeanit.com
Python의 Special method들과 그들을 호출하는 build-in function들.
이 대응관계는 Python의 공식 document만 읽어서는 전체적으로 파악하기가 어렵다.
Python 공식 doc에서 __next__를 검색하면,
https://docs.python.org/3/library/stdtypes.html#typeiter
Built-in Types — Python 3.11.0 documentation
Built-in Types The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that
docs.python.org
iterator 객체의 next item을 반환한다는 설명만 나올 뿐이다.
next()를 검색해야
https://docs.python.org/3/library/functions.html?highlight=next#next
Built-in Functions — Python 3.11.0 documentation
Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs(x, /) Return the absolute value of a number. The argument may be an integer, a floating p
docs.python.org
아, 내가 정의한 class에 __next__ method를 정의함으로써
해당 class의 객체를 iterator로 만들 수 있구나! 하고 알 수 있다.
'Python' 카테고리의 다른 글
| [Python] Iterator (0) | 2024.10.23 |
|---|---|
| [Python] pyenv로 가상환경 구축하기. (0) | 2023.09.19 |
| [Python] Decorator3. Property (0) | 2022.11.16 |
| [Python] Decorator 2. abstractmethod() (0) | 2022.11.15 |
| [Python] Decorator (0) | 2022.11.07 |