선택적 매개 변수를 함수에 전달하는 방법이 있습니까?
파이썬에서 선택적 매개 변수를 호출하는 동안 함수에 선택적 매개 변수를 전달하는 방법이 있으며 함수 정의에 "선택적 매개 변수가 전달 된 경우에만"
파이썬이 문서, 7.6. 함수 정의 는 호출자가 선택적 매개 변수를 제공했는지 여부를 감지하는 몇 가지 방법을 제공합니다.
먼저 특수 형식 매개 변수 구문을 사용할 수 있습니다 *. 함수 정의에 형식 매개 변수 앞에 single이 오는 *경우 Python 은 해당 형식 매개 변수를 선행 형식 매개 변수와 일치하지 않는 위치 매개 변수 (튜플)로 채 웁니다. 함수 정의에 앞에 공식 매개 변수가있는 경우, **Python은 사전 매개 변수와 일치하지 않는 키워드 매개 변수로 해당 매개 변수를 채 웁니다 (dict). 함수의 구현은 원하는 종류의 "선택적 매개 변수"에 대해 이러한 매개 변수의 내용을 확인할 수 있습니다.
예를 들어, 여기에 함수의 opt_fun두 위치 매개 변수 소요 x1하고 x2"선택"라는 또 다른 키워드 매개 변수, 그리고 외모.
>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
... if ('optional' in keyword_parameters):
... print 'optional parameter found, it is ', keyword_parameters['optional']
... else:
... print 'no optional parameter, sorry'
...
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry
둘째, None발신자가 절대 사용하지 않는 특정 값의 기본 매개 변수 값을 제공 할 수 있습니다. 매개 변수에이 기본값이 있으면 호출자가 매개 변수를 지정하지 않은 것입니다. 매개 변수가 기본값이 아닌 경우 호출자로부터 온 것임을 알 수 있습니다.
def my_func(mandatory_arg, optional_arg=100):
print(mandatory_arg, optional_arg)
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
나는 이것을 사용하는 것보다 더 읽기 쉽습니다 **kwargs.
인수가 전혀 전달되지 않았는지 확인하기 위해 사용자 정의 유틸리티 객체를 기본값으로 사용합니다.
MISSING = object()
def func(arg=MISSING):
if arg is MISSING:
...
def op(a=4,b=6):
add = a+b
print add
i)op() [o/p: will be (4+6)=10]
ii)op(99) [o/p: will be (99+6)=105]
iii)op(1,1) [o/p: will be (1+1)=2]
Note:
If none or one parameter is passed the default passed parameter will be considered for the function.
매개 변수에 기본값을 지정하려면 ()에 값을 지정하십시오. (x = 10)과 같습니다. 그러나 중요한 것은 먼저 논쟁을해야하고 기본값은 필수입니다.
예.
(y, x = 10)
그러나
(x = 10, y)가 잘못되었습니다
You can specify a default value for the optional argument with something that would never passed to the function and check it with the is operator:
class _NO_DEFAULT:
def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()
def func(optional= _NO_DEFAULT):
if optional is _NO_DEFAULT:
print("the optional argument was not passed")
else:
print("the optional argument was:",optional)
then as long as you do not do func(_NO_DEFAULT) you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:
# these two work the same as using **
func()
func(optional=1)
# the optional argument can be positional or keyword unlike using **
func(1)
#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)
'programing tip' 카테고리의 다른 글
| iPhone에서 NSString에 대한 AES 암호화 (0) | 2020.07.10 |
|---|---|
| C #에서 'T : class'는 무엇을 의미합니까? (0) | 2020.07.10 |
| 안드로이드 아카이브 라이브러리 (ar) vs 표준 jar (0) | 2020.07.10 |
| 정확히 파이썬의 file.flush ()가 무엇을하고 있습니까? (0) | 2020.07.10 |
| 리눅스에서 gcc를위한 간단한 makefile을 어떻게 만드나요? (0) | 2020.07.10 |