문제

How do I get the mutable default arguments tuple in Python 3?

def foo(x=[]):
    pass

Failed Attempt:

foo.func_defaults

Error:

AttributeError: 'function' object has no attribute 'func_defaults'
도움이 되었습니까?

해결책

You should be using __defaults__, like this

def foo(x=[]):
    x.append(1)

foo()
foo()
print(foo.__defaults__)
# ([1, 1],)

Quoting from the data model,

__defaults__

A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value.

It means that, when you have a function which doesn't have a default parameter, then __defaults__ will be None

def foo():
    pass

print(foo.__defaults__)
# None
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top