__init__ 메서드 Python에서는 클래스의 객체를 초기화하는 데 사용됩니다. 생성자라고도 합니다.
__init__ 메소드의 개념을 완전히 이해하려면 다음 사항을 숙지해야 합니다.
전제 조건 – Python 클래스 및 객체 , 본인
Python에서 __init__ 란 무엇입니까?
__init__ 메서드 의 기본 생성자와 같습니다. C++ 그리고 자바 . 생성자는 객체의 상태를 초기화하는 데 사용됩니다.
생성자의 임무는 클래스의 객체가 생성될 때 클래스의 데이터 멤버를 초기화(값 할당)하는 것입니다.
메소드와 마찬가지로 생성자에도 객체 생성 시 실행되는 명령문(예: 명령어) 모음이 포함되어 있습니다. 클래스의 객체가 인스턴스화되자마자 실행됩니다.
이 메서드는 개체로 수행하려는 초기화를 수행하는 데 유용합니다.
파이썬3
파이썬은 숫자형이다
# A Sample class with init method> class> Person:> ># init method or constructor> >def> __init__(>self>, name):> >self>.name>=> name> ># Sample Method> >def> say_hi(>self>):> >print>(>'Hello, my name is'>,>self>.name)> p>=> Person(>'Nikhil'>)> p.say_hi()> |
>
>
산출:
Hello, my name is Nikhil>
코드 이해
위의 예에서는 Nikhil이라는 사람이 생성되었습니다. 사람을 생성하는 동안 Nikhil이 인수로 전달되며, 이 인수는 개체를 초기화하기 위해 __init__ 메서드에 전달됩니다.
self 키워드는 클래스의 인스턴스를 나타내며 속성을 지정된 인수와 바인딩합니다. 마찬가지로, 다양한 이름을 인수로 전달하여 Person 클래스의 많은 개체를 만들 수 있습니다.
아래는 __의 예입니다. 매개변수가 있는 Python의 init__
Python의 __init__ 메소드 예
Python에서 __init__ 메소드의 몇 가지 예를 살펴보겠습니다.
파이썬3
피트 데이비슨은 몇 살입니까?
# A Sample class with init method> class> Person:> ># init method or constructor> >def> __init__(>self>, name):> >self>.name>=> name> ># Sample Method> >def> say_hi(>self>):> >print>(>'Hello, my name is'>,>self>.name)> # Creating different objects> p1>=> Person(>'Nikhil'>)> p2>=> Person(>'Abhinav'>)> p3>=> Person(>'Anshul'>)> p1.say_hi()> p2.say_hi()> p3.say_hi()> |
>
>
산출:
Hello, my name is Nikhil Hello, my name is Abhinav Hello, my name is Anshul>
__init__ 상속이 포함된 메서드
계승 한 클래스가 다른 클래스의 속성을 파생하거나 상속하는 기능입니다. __init__이 상속에서 어떻게 작동하는지 알아보기 위해 아래 예제를 살펴보겠습니다.
파이썬3
10억분의 0은 몇 개야?
# Python program to> # demonstrate init with> # inheritance> class> A(>object>):> >def> __init__(>self>, something):> >print>(>'A init called'>)> >self>.something>=> something> class> B(A):> >def> __init__(>self>, something):> ># Calling init of parent class> >A.__init__(>self>, something)> >print>(>'B init called'>)> >self>.something>=> something> obj>=> B(>'Something'>)> |
>
>
산출:
A init called B init called>
따라서 상위 클래스 생성자가 먼저 호출됩니다. 그러나 Python에서는 상위 클래스 생성자가 항상 먼저 호출되는 것이 필수는 아닙니다.
부모 또는 자식 클래스에 대해 __init__ 메서드가 호출되는 순서는 수정할 수 있습니다. 이는 자식 클래스 생성자의 본문 다음에 부모 클래스 생성자를 호출하여 간단하게 수행할 수 있습니다.
예:
파이썬3
자바 정수를 문자열로 변환
# Python program to> # demonstrate init with> # inheritance> class> A(>object>):> >def> __init__(>self>, something):> >print>(>'A init called'>)> >self>.something>=> something> class> B(A):> >def> __init__(>self>, something):> >print>(>'B init called'>)> >self>.something>=> something> ># Calling init of parent class> >A.__init__(>self>, something)> obj>=> B(>'Something'>)> |
>
>
산출:
B init called A init called>
읽다 : Python의 상속
우리는 Python에서 __init__을 다루고, __init__를 사용하는 방법을 논의했으며, Python에서 __init__ 메서드를 사용하는 몇 가지 예도 살펴보았습니다.
생성자는 OOP에서 중요한 개념이며 __init__ 메서드는 생성자와 매우 유사합니다.
이 기사가 __init__ 방법을 배우는 데 도움이 되기를 바라며 프로젝트에서 이를 사용할 수 있을 것입니다.
관련 기사
- __init__()는 Python의 비공개 메서드인가요?
- __init__과 __call__의 차이점은 무엇입니까?
- __new__(파이썬)