Nice programing

Python의 함수 매개 변수에 대한 기본값

nicepro 2020. 12. 30. 20:23
반응형

Python의 함수 매개 변수에 대한 기본값


중복 가능성 :
인스턴스 메소드의 결과로 매개 변수의 기본값

파이썬에서 함수 매개 변수에 기본값을 설정할 수 있지만 :

def my_function(param_one='default')
    ...

현재 인스턴스 (self)에 액세스 할 수없는 것 같습니다.

class MyClass(..):

    def my_function(self, param_one=self.one_of_the_vars):
        ...

내 질문 :

  • 함수에서 기본 매개 변수를 설정하기 위해 현재 인스턴스에 액세스 할 수 없다는 것이 사실입니까?
  • 가능하지 않은 경우 : 이유는 무엇이며 이것이 향후 버전의 파이썬에서 가능할 것이라고 상상할 수 있습니까?

다음과 같이 작성되었습니다.

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

그리고 self함수가 시작될 때까지 실제로 존재하지 않는 특성으로 인해 파이썬에서는 절대 일어나지 않을 것이라고 말하는 것이 안전하다고 생각 합니다 ... (다른 모든 것과 마찬가지로 자체 정의에서 참조 할 수 없습니다)

예 : 당신은 할 수 없습니다 d = {'x': 3, 'y': d['x'] * 5}


당신이 생각하는 것보다 훨씬 더 많은 것이 있습니다. 기본값은 정적 (= 객체를 가리키는 상수 참조 )이고 정의의 어딘가에 저장 되는 것으로 간주합니다 . 메서드 정의 시간에 평가됨; 인스턴스가 아닌 클래스의 일부로 . 그들은 일정하기 때문에 self.

여기에 예가 있습니다. 직관적이지 않지만 실제로는 완벽합니다.

def add(item, s=[]):
    s.append(item)
    print len(s)

add(1)     # 1
add(1)     # 2
add(1, []) # 1
add(1, []) # 1
add(1)     # 3

이것은 인쇄 1 2 1 1 3됩니다.

같은 방식으로 작동하기 때문에

default_s=[]
def add(item, s=default_s):
    s.append(item)

분명히을 수정하면 default_s이러한 수정 사항이 유지됩니다.

다음을 포함한 다양한 해결 방법이 있습니다.

def add(item, s=None):
    if not s: s = []
    s.append(item)

또는 다음을 수행 할 수 있습니다.

def add(self, item, s=None):
    if not s: s = self.makeDefaultS()
    s.append(item)

그러면 메서드 makeDefaultS가에 액세스 할 수 self있습니다.

또 다른 변형 :

import types
def add(item, s=lambda self:[]):
    if isinstance(s, types.FunctionType): s = s("example")
    s.append(item)

여기서의 기본값 s공장 기능 입니다.

You can combine all these techniques:

class Foo:
    import types
    def add(self, item, s=Foo.defaultFactory):
        if isinstance(s, types.FunctionType): s = s(self)
        s.append(item)

    def defaultFactory(self):
        """ Can be overridden in a subclass, too!"""
        return []

Default value for parameters are evaluated at "compilation", once. So obviously you can't access self. The classic example is list as default parameter. If you add elements into it, the default value for the parameter changes!

The workaround is to use another default parameter, typically None, and then check and update the variable.


There are multiple false assumptions you're making here - First, function belong to a class and not to an instance, meaning the actual function involved is the same for any two instances of a class. Second, default parameters are evaluated at compile time and are constant (as in, a constant object reference - if the parameter is a mutable object you can change it). Thus you cannot access self in a default parameter and will never be able to.

ReferenceURL : https://stackoverflow.com/questions/13195989/default-values-for-function-parameters-in-python

반응형