Python의 생성자

전제 조건: Python의 객체지향 프로그래밍, 객체지향 파이썬3

파이썬3




class> GeekforGeeks:> > # default constructor> > def> __init__(> self> ):> > self> .geek> => 'GeekforGeeks'> > # a method for printing data members> > def> print_Geek(> self> ):> > print> (> self> .geek)> # creating object of the class> obj> => GeekforGeeks()> # calling the instance method using the object obj> obj.print_Geek()>

산출

GeekforGeeks 

의 예 매개변수화된 생성자:

파이썬3




class> Addition:> > first> => 0> > second> => 0> > answer> => 0> > # parameterized constructor> > def> __init__(> self> , f, s):> > self> .first> => f> > self> .second> => s> > def> display(> self> ):> > print> (> 'First number = '> +> str> (> self> .first))> > print> (> 'Second number = '> +> str> (> self> .second))> > print> (> 'Addition of two numbers = '> +> str> (> self> .answer))> > def> calculate(> self> ):> > self> .answer> => self> .first> +> self> .second> # creating object of the class> # this will invoke parameterized constructor> obj1> => Addition(> 1000> ,> 2000> )> # creating second object of same class> obj2> => Addition(> 10> ,> 20> )> # perform Addition on obj1> obj1.calculate()> # perform Addition on obj2> obj2.calculate()> # display result of obj1> obj1.display()> # display result of obj2> obj2.display()>

산출

First number = 1000 Second number = 2000 Addition of two numbers = 3000 First number = 10 Second number = 20 Addition of two numbers = 30 

예:

파이썬




class> MyClass:> > def> __init__(> self> , name> => None> ):> > if> name> is> None> :> > print> (> 'Default constructor called'> )> > else> :> > self> .name> => name> > print> (> 'Parameterized constructor called with name'> ,> self> .name)> > > def> method(> self> ):> > if> hasattr> (> self> ,> 'name'> ):> > print> (> 'Method called with name'> ,> self> .name)> > else> :> > print> (> 'Method called without a name'> )> # Create an object of the class using the default constructor> obj1> => MyClass()> # Call a method of the class> obj1.method()> # Create an object of the class using the parameterized constructor> obj2> => MyClass(> 'John'> )> # Call a method of the class> obj2.method()>

산출

Default constructor called Method called without a name ('Parameterized constructor called with name', 'John') ('Method called with name', 'John') 

설명:

이 예제에서는 기본 생성자와 매개변수화된 생성자를 모두 사용하여 MyClass 클래스를 정의합니다. 기본 생성자는 매개변수가 전달되었는지 여부를 확인하고 그에 따라 콘솔에 메시지를 인쇄합니다. 매개변수화된 생성자는 단일 매개변수 이름을 취하고 객체의 name 속성을 해당 매개변수의 값으로 설정합니다.

또한 객체에 name 속성이 있는지 확인하고 그에 따라 메시지를 콘솔에 인쇄하는 method() 메서드를 정의합니다.

두 가지 유형의 생성자를 사용하여 MyClass 클래스의 두 개체를 만듭니다. 먼저 기본 생성자를 사용하여 개체를 생성합니다. 기본 생성자는 콘솔에 호출된 기본 생성자라는 메시지를 인쇄합니다. 그런 다음 이 개체에 대해 method() 메서드를 호출하면 이름 없이 Method Called라는 메시지가 콘솔에 인쇄됩니다.

다음으로 매개변수화된 생성자를 사용하여 객체를 생성하고 John이라는 이름을 전달합니다. 생성자가 자동으로 호출되고 John이라는 이름으로 호출된 Parameterized constructor라는 메시지가 콘솔에 인쇄됩니다. 그런 다음 이 객체에 대해 method() 메서드를 호출합니다. 그러면 Method Called with name John이라는 메시지가 콘솔에 인쇄됩니다.

전반적으로 이 예제는 Python의 단일 클래스에서 두 가지 유형의 생성자를 모두 구현할 수 있는 방법을 보여줍니다.

Python에서 생성자를 사용하면 다음과 같은 이점이 있습니다.

    객체 초기화 : 생성자는 클래스의 객체를 초기화하는 데 사용됩니다. 이를 통해 속성이나 속성에 대한 기본값을 설정할 수 있으며 사용자 정의 데이터로 개체를 초기화할 수도 있습니다. 구현하기 쉬움: 생성자는 Python에서 구현하기 쉽고 __init__() 메서드를 사용하여 정의할 수 있습니다.
  • 가독성 향상: 생성자는 어떤 값이 초기화되고 어떻게 초기화되는지 명확하게 하여 코드의 가독성을 향상시킵니다.
  • 캡슐화 : 생성자를 사용하면 객체의 속성이 올바르게 제어된 방식으로 초기화되도록 하여 캡슐화를 시행할 수 있습니다.

Python에서 생성자를 사용할 때의 단점:

    오버로딩이 지원되지 않음: 다른 객체 지향 언어와 달리 Python은 메서드 오버로딩을 지원하지 않습니다. 이는 단일 클래스에 서로 다른 매개변수를 가진 여러 생성자를 가질 수 없음을 의미합니다. 제한된 기능: Python의 생성자는 다른 프로그래밍 언어의 생성자와 비교하여 기능이 제한됩니다. 예를 들어 Python에는 public, private 또는 protected와 같은 액세스 한정자가 있는 생성자가 없습니다. 생성자는 불필요할 수 있습니다. 어떤 경우에는 속성의 기본값이 충분할 수 있으므로 생성자가 필요하지 않을 수도 있습니다. 이러한 경우 생성자를 사용하면 코드가 불필요하게 복잡해질 수 있습니다.

전반적으로 Python의 생성자는 객체를 초기화하고 캡슐화를 적용하는 데 유용할 수 있습니다. 그러나 항상 필요한 것은 아니며 다른 프로그래밍 언어의 생성자와 비교하여 기능이 제한됩니다.