Common structure
def name(arg1, ... argN, kwarg1, ... kwargN, *args, **kwargs):
"""Short description
Long description...
"""
....operator1
....operatorN
....return value
Naming rules
myFunc() # bad
My_func # bad
100_top_users # SyntaxError
get_top_users() # ok
_fetch_data() # perhaps you shouldn't call that directly
Why need docstring
def test(a, b, c=3, d=4)
test() TypeError
test(1, 2) a=1, b=2, c=3, d=4
test(4, 10, c=22) a=4, b=10, c=22, d=4
test(a=6, b=5) a=6, b=5, c=3, d=4
test(d=4, a=1) TypeError
test(c=1, b=4, a=5) a=5, b=4, c=1, d=4
test(9, 8, 7) a=9, b=8, c=7, d=4
test(9, 8, 7, 6) a=9, b=8, c=7, d=6
What does function return
- Use return <value> statement
- There might be several return statements
- None if there is no return statement
- Use tuple to return multiple values
def func(foo, bar, baz=42):
if baz == 42:
return (False, "some-error")
else:
return (True, "OK")
ok, message = func(1, 2) False, "some-error"
ok, message = func(1, 2, baz=3) True, "OK"
Function is object
- Copy, delete function
- Pass it into a function call
- Might be either a key or value of a dict
- Has special attrs (__name__, __module__, etc)
def user_auth(user):
pass
def user_logout(user)
pass
actions = {"auth": user_auth, "logout": user_logout}
actions[action](user)
args, kwargs
params = {"name": "Ivan", "age": 29}
if ...
params["created_at"] = datetime.now()
if ...
params["friends"] = ["Joe", "Mary"]
create_user(**params)
create_user(name="Ivan", age=29,
created_at=datetime.now(),
friends=["Joe", "Mary"]
)
Never use mutable defaults!
def test(a=[]):
a.append(1)
print a
test() [1]
test() [1, 1]
test() [1, 1, 1]
test() [1, 1, 1, 1]
Lambdas
double = lambda x: 2 * x
map(double, [1, 2, 3]) [2, 4, 6]
calc = lambda (x, y, z): x * y - z
map(calc, [(1, 2, 3), (4, 5, 6)]) [-1, 14]
avg = lambda *args: sum(args) / float(len(args))
avg(1, 2, 3) 2.0
lambda x: pass SyntaxError
Вам ответят команда поддержки Хекслета или другие студенты.
Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно.
Наши выпускники работают в компаниях:
Зарегистрируйтесь или войдите в свой аккаунт