본문 바로가기
개발&코딩/Python

파이썬의 __init__() 의 역할 // python __init__(), constructor

by 우동이 2022. 6. 30.
300x250

객체지향언어인 파이썬은 객체지향프로그래밍을 하며(OOP)

Class 기반의 모델을 기반으로 코딩을 할 수 있습니다.

 

파이썬에서 보여지는 기초적인 클래스의 형태는 이러합니다.

class Human():
    '''
            Human information
    '''
    def __init__(self, name, age, tall): #생성자
        self._name = name
        self._age = age
        self._tall = tall
    



person1 = Human('David', 28, 170)

print(person1) # <__main__.Human object at 0x000001E59200EDA0>
print(person1._name) # person1's name print >> David

클래스 내부의 주석은 개발자간 코드 가독성을 위해 권장한다고 합니다.

클래스의 가장 첫번째는 __init__() 메소드가 위치합니다.

 

__init__() 메소드는 객체지향프로그래밍 언어의 새로운 오브젝트를 생성할 때 호출되어 내용의 초기화를 담당하는 

메소드라고 합니다.(wikipedia)

 

다른 말로 컨스트럭터(Constructor)로 불리우며 초기화를 담당하고

인스턴스 생성과 동시에 데이터를 초기화 합니다.

 

여기서 메소드는 클래스 내의 함수를 뜻하며

인스턴스는 클래스를 실체화 시킨 객체(인스턴스)를 뜻합니다.

인스턴스나 객체 같은 의미이며

메소드나 함수 둘다 같은 의미이며 혼용합니다.

 

def __init__(self):

또한 init 함수는 추가 인자를 받건 안받건 무조건 self라는 인자를 첫번째로 받습니다.

 

여기서 self 인자에 대해서는 지칭하는 말이 조금씩 차이가 있으나 

인스턴스 그 자신을 뜻한다고 보시면 됩니다.

 

즉 인스턴스를 초기화 하는 init 함수에서 self는 그 인스턴스를 초기화 하기 위해 

생성된 인스턴스를 받아오는 역할을 한다고 보고 있습니다.

 

    def __init__(self, name, age, tall): #생성자
        self._name = name
        self._age = age
        self._tall = tall

또한 위 클래스 코드에서 보면 

인스턴스 생성을 통해 받아온 인자들을 전부 초기화 해주고 있습니다.

 

 

person1 = Human('David', 28, 170)
print(person1._name) # person1's name print >> David

person1이라는 인스턴스를 생성하고 인자를 넘겨준 후 

init 함수가 name에 들어간 'David' 라는 값을 초기화 해서

객체의 _name 필드를 참조해 

David라는 값이 호출될 수 있습니다.


 

참고자료

 

Self in Python Class | What is the Use of Python Self?

The self in Python is used to represent the instance of the class. With this Self keyword in Python, you can access the attributes and methods of the class.

www.edureka.co

 

 

self in Python class - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

 

 

Python self 이해하기

Python으로 클래스를 생성할 때 자주 보이는 self에 대해 알아보겠습니다. 간단히 바로 요약하자면 self란 클래스의 인스턴스를 나타내는 변수입니다. 무슨 말인지는 천천히 예를 들면서 설명하겠

jsp-dev.tistory.com

 

 

PEP 257 – Docstring Conventions | peps.python.org

PEP 257 – Docstring Conventions Author: David Goodger , Guido van Rossum Discussions-To: Doc-SIG list Status: Active Type: Informational Created: 29-May-2001 Post-History: 13-Jun-2001 Table of Contents This PEP documents the semantics and conventions ass

peps.python.org

 

 

【Python】__init__ってなに?コンストラクタを理解する

今回はオブジェクト指向のプログラムでクラスを実装する際に必須なコンストラクタについて解説します。オブジェクト指…

ct-innovation01.xyz

 

300x250

댓글