logo

Python의 기본 인수

Python에서는 함수 인수가 기본값을 가질 수 있습니다. 인수 없이 함수를 호출하면 인수는 기본값을 가져옵니다.

기본 인수:

Python에는 함수 인수의 구문과 기본값을 나타내는 다른 방법이 있습니다. 기본값은 함수 호출 중에 인수 값이 전달되지 않으면 함수 인수가 해당 값을 사용함을 나타냅니다. 기본값은 형식의 할당(=) 연산자를 사용하여 할당됩니다. 키워드 이름 =값.
함수를 통해 이해해보자 학생 . 함수 학생 3개의 인수를 포함하며 그 중 2개의 인수에는 기본값이 할당됩니다. 따라서 기능은 학생 하나의 필수 인수를 허용합니다( 이름 ), 나머지 두 인수는 선택 사항입니다.



파이썬3








def> student(firstname, lastname>=>'Mark'>, standard>=>'Fifth'>):> >print>(firstname, lastname,>'studies in'>, standard,>'Standard'>)>

>

>


함수를 호출하는 동안 다음 사항을 염두에 두어야 합니다.

  1. 키워드 인수를 전달하는 경우 인수 순서가 중요합니다.
  2. 하나의 매개변수에는 하나의 값만 있어야 합니다.
  3. 전달된 키워드 이름은 실제 키워드 이름과 일치해야 합니다.
  4. 키워드가 아닌 인수가 포함된 함수를 호출하는 경우 순서가 중요합니다.

예시 #1: 키워드 인수 없이 함수 호출

파이썬3

피트 데이비슨 국적




def> student(firstname, lastname>=>'Mark'>, standard>=>'Fifth'>):> >print>(firstname, lastname,>'studies in'>, standard,>'Standard'>)> # 1 positional argument> student(>'John'>)> # 3 positional arguments> student(>'John'>,>'Gates'>,>'Seventh'>)> # 2 positional arguments> student(>'John'>,>'Gates'>)> student(>'John'>,>'Seventh'>)>

>

>

산출:

John Mark studies in Fifth Standard John Gates studies in Seventh Standard John Gates studies in Fifth Standard John Seventh studies in Fifth Standard>

첫 번째 호출에는 필수 인수가 하나만 있고 나머지 인수는 기본값을 사용합니다. 두 번째 통화에서는 표준 인수 값은 기본값에서 새로운 전달 값으로 대체됩니다. 함수의 두 번째, 세 번째, 네 번째 호출에서 인수의 순서가 중요하다는 것을 알 수 있습니다.

예제 #2: 키워드 인수를 사용하여 함수 호출

파이썬3




def> student(firstname, lastname>=>'Mark'>, standard>=>'Fifth'>):> >print>(firstname, lastname,>'studies in'>, standard,>'Standard'>)> # 1 keyword argument> student(firstname>=>'John'>)> # 2 keyword arguments> student(firstname>=>'John'>, standard>=>'Seventh'>)> # 2 keyword arguments> student(lastname>=>'Gates'>, firstname>=>'John'>)>

iskcon 전체 형태

>

>

산출:

John Mark studies in Fifth Standard John Mark studies in Seventh Standard John Gates studies in Fifth Standard>

첫 번째 호출에는 필수 키워드 인수가 하나만 있습니다. 두 번째 호출에서 하나는 필수 인수이고 다른 하나는 선택적(표준) 인수이며, 해당 값은 기본값에서 새 전달 값으로 대체됩니다. 세 번째 호출에서는 키워드 인수의 순서가 중요하지 않음을 알 수 있습니다.

예제 #3: 일부 잘못된 함수 호출

파이썬3




def> student(firstname, lastname>=>'Mark'>, standard>=>'Fifth'>):> >print>(firstname, lastname,>'studies in'>, standard,>'Standard'>)> # required argument missing> student()> # non keyword argument after a keyword argument> student(firstname>=>'John'>,>'Seventh'>)> # unknown keyword argument> student(subject>=>'Maths'>)>

>

>

위 코드는 다음과 같은 이유로 오류를 발생시킵니다.

  • 첫 번째 호출에서는 매개변수 값이 전달되지 않습니다. 이름 이는 필수 매개변수입니다.
  • 두 번째 호출에서는 키워드 인수 뒤에 키워드가 아닌 인수가 있습니다.
  • 세 번째 호출에서는 전달하는 키워드 인수가 실제 키워드 이름 인수와 일치하지 않습니다.

Python에서 가변 객체를 기본 인수 값으로 사용

이 작업은 매우 신중하게 수행되어야 합니다. 그 이유는 컨트롤이 함수에 도달할 때 인수의 기본값이 한 번만 평가되기 때문입니다.

처음으로 정의합니다. 그 이후에는 후속 함수 호출에서 동일한 값(또는 변경 가능한 객체)이 참조됩니다.
예제를 보면 상황이 훨씬 더 명확해질 것입니다.

파이썬3


팩토리얼 자바



# mutable default argument values example using python list> # itemName is the name of the item that we want to add to list> # that is being passed, or if it is not passed then appending in> # the default list> def> appendItem(itemName, itemList>=> []):> >itemList.append(itemName)> >return> itemList> print>(appendItem(>'notebook'>))> print>(appendItem(>'pencil'>))> print>(appendItem(>'eraser'>))>

>

>

산출

['notebook'] ['notebook', 'pencil'] ['notebook', 'pencil', 'eraser']>

목록을 전달하지 않을 때 각 함수 호출에서 새 목록이 생성된다고 가정하면 예상한 결과는 무엇입니까?

['공책']

['연필']

['지우개']

그러나 함수가 호출될 때마다 프로그램의 실제 출력에서 ​​볼 수 있듯이 동일한 목록이 사용되며 새 호출에 대해 새 목록이 만들어지지 않습니다.

사전을 사용한 예

파이썬3


정의되지 않은 경사



# mutable default argument values example using python dictionary> # itemName is the name of item and quantity is the number of such> # items are there> def> addItemToDictionary(itemName, quantity, itemList>=> {}):> >itemList[itemName]>=> quantity> >return> itemList> print>(addItemToDictionary(>'notebook'>,>4>))> print>(addItemToDictionary(>'pencil'>,>1>))> print>(addItemToDictionary(>'eraser'>,>1>))>

>

>

산출

{'notebook': 4} {'notebook': 4, 'pencil': 1} {'notebook': 4, 'pencil': 1, 'eraser': 1}>

각 함수 호출에서 새 사전이 생성된다고 가정하면 예상한 결과

{'노트북': 4}

{'연필': 1}

{'지우개': 1}

그러나 프로그램의 실제 출력이 다르며 이는 각 후속 호출에서 동일한 사전이 사용됨을 나타냅니다.

여기서 중요한 점은 그러한 시나리오를 피해야 한다는 것입니다.

모범 사례

기본값을 없음으로 할당한 다음 예상되는 목록 또는 사전 인수가 없음인지 아닌지 함수를 확인하세요.

아무것도 없으면 요구 사항에 따라 목록이나 사전을 할당하십시오.

파이썬3


자바 목록 상자



# using None as values of the default arguments> print>(>'#list'>)> def> appendItem(itemName, itemList>=>None>):> >if> itemList>=>=> None>:> >itemList>=> []> >itemList.append(itemName)> >return> itemList> print>(appendItem(>'notebook'>))> print>(appendItem(>'pencil'>))> print>(appendItem(>'eraser'>))> # using None as value of default parameter> print>(>' #dictionary'>)> def> addItemToDictionary(itemName, quantity, itemList>=> None>):> >if> itemList>=>=> None>:> >itemList>=> {}> >itemList[itemName]>=> quantity> >return> itemList> print>(addItemToDictionary(>'notebook'>,>4>))> print>(addItemToDictionary(>'pencil'>,>1>))> print>(addItemToDictionary(>'eraser'>,>1>))>

>

>

산출

#list ['notebook'] ['pencil'] ['eraser'] #dictionary {'notebook': 4} {'pencil': 1} {'eraser': 1}>

여기에서 함수가 호출되고 목록이나 사전이 함수에 인수로 전달되지 않을 때마다 새 목록이나 사전이 생성된다는 것을 명확하게 볼 수 있습니다.