Created
December 10, 2012 19:49
-
-
Save miped/4252870 to your computer and use it in GitHub Desktop.
kwargs og args
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
def func0(a, b, c): | |
print "func0" | |
print "a", a, "b", b, "c", c | |
func0('a', 'b', 'c') | |
# catch-all | |
def func1(*args, **kwargs): | |
print "func1" | |
print args | |
print kwargs | |
func1('a', 'b', d=1, e=2) | |
# man kan også bare tage nogle af dem og lade den fange resten, kan dog ikke blande *args, normale keyword args og **kwargs | |
def func2(a, *args, **kwargs): | |
print "func2" | |
print "a", a | |
print args | |
print kwargs | |
func2('a', 'b', d=1, e=2) | |
# det her er meget normalt, 2 required, 2 optional og en catch-all | |
def func3(a, b, d=None, e=None, **kwargs): | |
print "func3" | |
print "a", a, "b", b | |
print "d", d, "e", e | |
print kwargs | |
# man kan også bruge det når man kalder | |
arguments = ['a', 'b', 'c'] | |
keywords = {'d': 1, 'e': 2, 'f': 3} | |
func0(*arguments) | |
func1(*arguments) # positional arguments pakkes ud med * (skal være en liste eller tuple) | |
func1(**keywords) # keyword arguments pakkes ud med ** (dict eller subclass af dict) | |
func1(arguments) # det her er nok ikke det du vil | |
func1(keywords) # det er det her nok heller ikke | |
func2(*arguments, **keywords) # all together now | |
func3('a', 'b', **keywords) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment