티스토리 뷰

개발/이론 공부

Python) __init__ , self 란?

Ikhyeon IT 2022. 11. 10. 14:41

__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 변수를 불러다 사용할 수 있는 것 이다.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함