- Оголошення функції - def_def
- Порядок оголошення та виклику - def_order
- Повернення результату - def_return
- Перевизначення функції - def_redef
- Збереження функції у перемінінй - def_storing
- Видимість перемінних - def_var_visibility
- Аргументи - def_args
- Зміна переданого аргументу - def_args_ch
- Детальныще про атрибути функції - def_what
- Варіанти походження функцій - def_source
- Місцеположення оголошення - def_placement
- Анонімні функції - def_lambda
Last active
August 29, 2015 14:22
-
-
Save conmute/5d285d6ac69f6b5cede2 to your computer and use it in GitHub Desktop.
functions in Python
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 C2F(c): | |
return c * 9/5 + 32 | |
print C2F(100) | |
print C2F(0) | |
print C2F(30) | |
""" | |
Параметр зі значення по замовчуванню | |
""" | |
def power(x, y=2): | |
r = 1 | |
for i in range(y): | |
r = r * x | |
return r | |
print power(3) | |
print power(3, 3) | |
print power(5, 5) | |
""" | |
Коли параметрів декілька, слід слідкувати за їх порядком при виклику функцій. | |
Як альтернативний варіант, ми можемо викликати функцію в стилі ключ=значення | |
""" | |
def display(name, age, sex): | |
print "Name: ", name | |
print "Age: ", int(age) | |
print "Sex: ", sex | |
print "---" | |
# У випадку невірного порядку, може виникнути помилка. | |
# У нашому варіанту age повинен бути обов’язково числом | |
display("Lary", 43, "Male") | |
display("Joan", 24, "Female") | |
# Передаючи параметри по назвам... | |
display(age=43, name="Lary", sex="M") | |
display(name="Joan", age=24, sex="F") | |
# В перемішку | |
display("Joan", sex="F", age=24) | |
# Але ні вякому разі не треба робити так! | |
# display(age=24, name="Joan", "F") # error! | |
""" | |
Параметри функції як список в одній перемінній | |
""" | |
def sum(*args): | |
'''Function returns the sum | |
of all values''' | |
r = 0 | |
for i in args: | |
r += i | |
return r | |
print sum.__doc__ | |
print sum(1, 2, 3) | |
l = [1, 2, 3, 4, 5] | |
print sum(*l) | |
""" | |
Параметри функції як словник в одній перемінній | |
""" | |
def display(**details): | |
for i in details: | |
print "%s: %s" % (i, details[i]) | |
display(name="Lary", age=43, sex="M") | |
print "---" | |
d = {"name":"Harry", "age":14, "sex":"M"} | |
display(**d) | |
print "---" | |
""" | |
А тепер змішаймо це все | |
""" | |
def display(arg1, arg2, *args, **details): | |
print arg1, arg2 | |
for i in details: | |
print "%s: %s" % (i, details[i]) | |
r = 0 | |
for i in args: | |
r += i | |
print r | |
display("val1", "val2", 3, 4, 5, name="Lary", age=43, sex="M") | |
l = [1,2,3] | |
d = { | |
"name": "Mary", | |
"age": 22, | |
"sex": "F" | |
} | |
display("val ver 1", "val ver 2", *l, **d) |
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 -*- | |
""" | |
Передаючи перемінну до функції, ми маємо змогу змінити її значення | |
Всі аргументи функцій не копіюся, а вказують на передане значення, | |
саме тому є можливість їх змінити. В народі це називають вказівниками. | |
""" | |
n = [1, 2, 3, 4, 5] | |
print "Original list:", n | |
def f(x): | |
x.pop() | |
x.pop() | |
x.insert(0, 0) | |
print "Inside f():", x | |
f(n) | |
print "After function call:", n |
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 -*- | |
""" | |
Оголошення функцій. | |
Фінкція повертає значення. Для того щоб це зробити слід використати | |
ключове слово `return`. Якщо його не використовувати функція повертати | |
значення None. | |
Саме тому можна значення повернен від функції присвоїти перемінній. | |
""" | |
def showModuleName(): | |
print __doc__ | |
def getModuleFile(): | |
return __file__, 123 | |
a = showModuleName() | |
b = getModuleFile() | |
print a, b |
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 -*- | |
""" | |
Анонімні функції. | |
Оскільки функція являєтсья об’єктом є сенс анонімних функцій. | |
Таких котру будуть вживатись у програмі один раз. | |
Для цього мовою python використовуэться ключове слово `lambda`. | |
""" | |
y = 6 | |
z = lambda x: x * y | |
# def z(x): | |
# return x * y | |
print z(8) | |
# Те саме мовою JavaScript | |
# z = function(x) {return x * y} | |
# І варіант одночасного оголошеня і передачі функції як перемінну | |
# smth(function(x) {return x * y}) | |
# usage: | |
def C2S(t): | |
return (9.0/5)*t + 32 | |
cs = [-10, 0, 15, 30, 40] | |
ft = map(C2S, cs) | |
ft = map(lambda t: (9.0/5)*t + 32, cs) | |
print cs | |
print ft |
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 f1(): | |
print "f1()" | |
f1() | |
# f2() # ERROR! | |
def f2(): | |
print "f2()" | |
f2() # now no error |
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 -*- | |
""" | |
Місця де оголошеємо функції. | |
""" | |
"Функція як метод класу" | |
class Some: | |
@staticmethod | |
def f(): | |
print "f() method" | |
"Функція як функція...." | |
def f(): | |
print "f() function" | |
"Функція у функції... чому б ні?" | |
def g(): | |
def f(): | |
print "f() inner function" | |
f() | |
Some.f() | |
f() | |
g() |
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 -*- | |
""" | |
Функція свого роду це перемінна. А отже працювати ми можема з нею так само. | |
Тут є демонстрація прикладу перевизначення функції. | |
""" | |
from time import gmtime, strftime | |
# Початкове оголошення функції | |
def showMessage(msg): | |
print msg | |
showMessage("Ready.") | |
# Переоголосимо з іншим функціоналом | |
def showMessage(msg): | |
print strftime("%H:%M:%S", gmtime()), | |
print msg | |
showMessage("Processing.") | |
# І тепер функцію "замістимо" числом, щоб няглядно продемонструвати що | |
# це також перемінна | |
showMessage = 1 | |
print showMessage |
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 -*- | |
""" | |
Розглянемо повернення результату функції. | |
Щоб функція повертала значення відмінне від `None`, слід використати | |
фразу `return`. | |
""" | |
def showMessage(msg): | |
print msg | |
def cube(x): | |
return x * x * x | |
x = cube(3) | |
print x | |
showMessage("Computation finished.") | |
print showMessage("Ready.") | |
# more then one | |
n = [1, 2, 3, 4, 5] | |
""" | |
Можна повернути декілька значень, але в такому випадку | |
присвоювати прийдеться стільки ж | |
""" | |
def stats(x): | |
mx = max(x) | |
mn = min(x) | |
ln = len(x) | |
sm = sum(x) | |
return mx, mn, ln, sm | |
mx, mn, ln, sm = stats(n) | |
print stats(n) | |
print mx, mn, ln, sm |
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 -*- | |
""" | |
Походження функції. | |
Функцію ми можемо створити. | |
ми можем імпортувати від модулю | |
або використати вже глобально доступну | |
""" | |
from math import sqrt | |
def cube(x): | |
return x * x * x | |
print abs(-1) | |
print cube(9) | |
print sqrt(81) |
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 f(): | |
pass | |
def g(): | |
pass | |
def h(f): | |
print id(f) | |
a = (f, g, h) | |
for i in a: | |
print i | |
h(f) | |
h(g) |
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 -*- | |
""" | |
Видимість перемінних в функції та поза нею. | |
""" | |
""" | |
Якщо оголосити всередині функції перемінну з такою ж назвою, | |
то це не буде переприсвоєння, а створення нової змінної в межах функції | |
хоч і з такою ж назвою | |
""" | |
name = "Jack" | |
def f(): | |
name = "Robert" | |
print "Within function", name | |
f() | |
print "Outside function", name | |
print "---" | |
# v2 | |
""" | |
Перемінна "зовні", і її видимість всередині функції | |
""" | |
name = "Jack" | |
def f(): | |
print "Within function", name | |
print "Outside function", name | |
f() | |
print "---" | |
# v3 | |
""" | |
Зробити перемінну "вище" доступну всередині функції | |
за допомогою команди `global`. | |
""" | |
name = "Jack" | |
def f(): | |
global name | |
name = "Robert" | |
print "Within function", name | |
print "Outside function", name | |
f() | |
print "Outside function", name |
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 -*- | |
""" | |
Що ж таке функція для `python`? | |
Кожна створенна функція, є об’єктом. В нього є свої методи та атрибути. | |
""" | |
from types import FunctionType | |
def f(): | |
"""This function prints a message """ | |
print "Today it is a cloudy day" | |
"Об’єкт `функція` наслідується глобальним, самим першим об’єктом `object`" | |
print isinstance(f, FunctionType) | |
print isinstance(f, object) | |
"Дістати унікальний ідентифікатор перемінної. В кожної змінної воно своє" | |
print id(f) | |
print f.func_doc | |
print f.func_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment