Skip to content

Instantly share code, notes, and snippets.

@dketov
Created December 13, 2011 14:21
Show Gist options
  • Save dketov/1472278 to your computer and use it in GitHub Desktop.
Save dketov/1472278 to your computer and use it in GitHub Desktop.
Передача аргументов
# -*- encoding: utf-8 -*-
"""
Формальные и фактические параметры
"""
def try_to_change(n):
n = 'Changed'
name = 'Init'
try_to_change(name)
print name
# -*- encoding: utf-8 -*-
"""
Полиморфизм аргументов
"""
def times(x, y): # create and assign function
return x * y # body executed when called
print times('Ni', 4) # functions are 'typeless'
# -*- encoding: utf-8 -*-
"""
Передача изменяемых и неизменяемых типов
"""
def changer(x, y):
x = 2 # changes local name's value only
y[0] = 'spam' # changes shared object in place
X = 1
L = [1, 2]
changer(X, L) # pass immutable and mutable
print X, L
L = [1, 2]
changer(X, L[:]) # pass a copy
print X, L
# -*- encoding: utf-8 -*-
"""
Способы передачи параметров
"""
def echo(*args, **kwargs): print args, kwargs
print echo(1, 2, a=3, b=4)
pargs = (1, 2)
kargs = {'a':3, 'b':4}
print apply(echo, pargs, kargs)
print apply(echo, args) # traditional: tuple
print func(*args) # new apply-like syntax
print echo(*pargs, **kargs) # keyword dictionaries too
print echo(0, *pargs, **kargs) # normal, *tuple, **dictionary
# -*- encoding: utf-8 -*-
"""
Значения параметров по умолчанию
"""
# The default values are evaluated at the point of function definition in the
# defining scope, so that
i = 5
def f(arg=i):
print arg
i = 6
f()
# positional parameters
# parameters with default values
def birthday2(name = "Jackson", age = 1):
print "Happy birthday,", name, "!", " I hear you're", age, "today.\n"
birthday2()
birthday2(name = "Katherine")
birthday2(age = 12)
birthday2(name = "Katherine", age = 12)
birthday2("Katherine", 12)
# -*- encoding: utf-8 -*-
"""
Списки параметров
"""
def f(*args): print args
f()
f(1)
f(1,2,3,4)
# -*- encoding: utf-8 -*-
"""
Упаковка параметров
"""
print range(3, 6) # normal call with separate arguments
args = [3, 6]
print range(*args) # call with arguments unpacked from a list
# -*- encoding: utf-8 -*-
"""
Передача параметров в виде словаря
"""
def f(**args): print args
print f()
print f(a=1, b=2)
def add(x, y): return x + y
params = (1, 2)
add(*params)
params = {'name': 'Sir Robin', 'greeting': 'Well met'}
def with_stars(**kwds):
print kwds['name'], 'is', kwds['age'], 'years old'
def without_stars(kwds):
print kwds['name'], 'is', kwds['age'], 'years old'
args = {'name': 'Mr. Joe', 'age': 42}
with_stars(**args)
without_stars(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment