티스토리 뷰
__init__
= initialize 를 표현한 구문이다.
ititialize의 의미는 기본값 설정하기 라는 뜻에 가깝다.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self, value):
self.head = Node(value)
def append(self, value):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(value)
def print_all(self):
cur = self.head
while cur is not None:
print(cur.data)
cur = cur.next
def get_node(self, index):
node = self.head
count = 0
while count < index:
node = node.next
count +=1
return node
linked_list = LinkedList(5)
linked_list.append(12)
print(linked_list.get_node(1).data)
위 코드는 Linked List를 클래스를 이용해 구현한 것이다.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self, value):
self.head = Node(value)
위 부분에서 __init__ 은 self,data 라는 값을 받는다.
여기서 self는 __init__이 받는 실질적인 주요 변수인 data를 클래스 전체가 사용할 수 있도록 만들기 위함이다.
def append(self, value):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(value)
def print_all(self):
cur = self.head
while cur is not None:
print(cur.data)
cur = cur.next
def get_node(self, index):
node = self.head
count = 0
while count < index:
node = node.next
count +=1
return node
만약 self를 사용하지 않고 data 만을 사용한다면 위 메소드(method)에서 __init__에서 받은 data 를 공유할 수 없게 된다.
그렇기에 파이썬 에서는 __init__함수가 첫 번째 변수로 무조건 해당 클래스를 스스로 받도록 설정한 것이다.
그렇기 때문에 메서드 에도 self 를 붙혀서 __init__에서 받은 data 변수를 불러다 사용할 수 있는 것 이다.
'개발 > 이론 공부' 카테고리의 다른 글
| 마이크로서비스 아키텍처(MSA) 란? (0) | 2023.10.18 |
|---|---|
| 객체 지향 프로그래밍 (Object Oriented Programing) 이란? (0) | 2022.11.12 |
| 배열 (Array), 연결리스트 (LinkedList) 란? (0) | 2022.11.09 |
| 자료구조와 알고리즘이란? (0) | 2022.11.08 |
| 오버로딩(Overloading) , 오버라이딩(Overriding) 이란? (0) | 2022.11.08 |
댓글