| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 | 31 |
Tags
- 715. Range Module
- t1
- Class
- Protocol
- Generator
- DWG
- Regular Expression
- 시바견
- Substring with Concatenation of All Words
- Python
- 프로그래머스
- concurrency
- 운영체제
- 30. Substring with Concatenation of All Words
- 109. Convert Sorted List to Binary Search Tree
- Decorator
- 밴픽
- Python Code
- Python Implementation
- iterator
- 43. Multiply Strings
- LeetCode
- Convert Sorted List to Binary Search Tree
- kaggle
- 컴퓨터의 구조
- shiba
- 315. Count of Smaller Numbers After Self
- attribute
- 파이썬
- data science
Archives
- Today
- Total
Scribbling
Python: First-class functions 1 본문
1. User defined Callable Object
User defined callable object can be defined as below. Magic method __call__ should be implemented.
import random
class BingoCage:
def __init__(self, items):
self.__items = list(items)
random.shuffle(self.__items)
def __pick(self):
try:
return self.__items.pop()
except IndexError:
raise LookupError('pick from empty BingoCage')
def __call__(self):
return self.__pick()
bingo = BingoCage(range(3))
bingo()
bingo()
bingo()
2. Inspect, Signature
signature object is used to inspect function objects' parameters.
signature object's bind method is to check whether the given parameters are valid for a certain function.
from inspect import signature
def func(param1:str, param2:'int > 0'=3, param3='hello world') -> str:
return param1 + str(param2) + param3
sig = signature(func)
for name, param in sig.parameters.items():
print(name, param.default)
param_dict1 = {
'param1': 'what?',
}
b1 = sig.bind(**param_dict1)
print(b1)
param_dict2 = {
'param1': 'what?',
'noparam': 3
}
b2 = sig.bind(**param_dict2)
print(b2)

3. Operators
1) basic operators
from functools import reduce
from operator import mul
def fact(n):
return reduce(mul, range(1, n+1))
print(fact(5))

2) itemgetter()
from operator import itemgetter
metro_data = [
('Seoul', 'South Korea'),
('Tokyo', 'Japan'),
('WS', 'US'),
]
for city in sorted(metro_data, key=itemgetter(1)):
print(city)
city_name = itemgetter(0)
for row in metro_data:
print(city_name(row))

3) attrgetter()
from collections import namedtuple
from operator import attrgetter
Person = namedtuple('Person', 'name age sex occupation')
p1 = Person('morgan', 28, 'm', 'engineer')
ag1 = attrgetter('name', 'occupation')
print(ag1(p1))

4. functools partial
functools.partial() is a high order function that creates a callable with given parameters.
from functools import partial
def power(n, exponent):
return n**exponent
square = partial(power, exponent=2)
print(square(3))