பாடம் 5 / 5 · Advanced Python · படிக்க 3 min · புதுப்பிக்கப்பட்டது
functools, introspection
reduce, partial, caching — Python-கிட்ட அதோட objects பத்தியே கேட்கிறது.
functools-ல இருக்கிற tools
python
from functools import reduce, partial, lru_cache
print(reduce(lambda a, b: a * b, [1, 2, 3, 4, 5]))
from_binary = partial(int, base=2)
print(from_binary("1010"))
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
Output
120
10
23416728348467685
reduceஒரு list-ஐ ஒரே value-ஆ மடிக்கும்: 1×2, அப்புறம் ×3, ×4, ×5. கூட்டலுக்கு சாதாரணsum()தெளிவானது.partialசில arguments-ஐ ஏற்கனவே நிரப்பின புது function-ஐ உருவாக்கும்.lru_cacheresults-ஐ ஞாபகம் வெச்சுக்கும், அதனால ஒவ்வொருfib(n)-ம் ஒரு தடவை தான் கணக்கிடப்படும். அது இல்லன்னாfib(80)நீங்க காத்திருக்க முடியாத அளவு நேரம் எடுக்கும்.
Introspection: objects பத்தி கேட்கிறது
python
value = [1, 2, 3]
print(type(value).__name__)
print(isinstance(value, (list, tuple)))
print(hasattr(value, "append"), callable(len))
print(getattr(value, "count")(2))
print([name for name in dir(value) if not name.startswith("_")][:4])
Output
list
True
True True
1
['append', 'clear', 'copy', 'count']
Program ஓடும்போதே Python எந்த object-ஐயும் விவரிக்கும்: அதோட type, என்ன attributes இருக்கு, கூப்பிட முடியுமா. getattr(obj, "name") run time-ல மட்டும் தெரியுற பேர் கொண்ட attribute-ஐ எடுக்கும் — user input-ல இருந்தோ file-ல இருந்தோ வர்ற பேர் மாதிரி.
python
def area(r):
"""Return the area of a circle of radius r."""
return 3.14159 * r * r
print(area.__name__)
print(area.__doc__)
Output
area
Return the area of a circle of radius r.
Note
அதனால தான் docstrings முக்கியம்: help(area)-ம் எல்லா code editors-ம் அதை படிக்கும். Interactive prompt-ல எதையும் ஆராய dir(), help() தான் வேகமான வழி — இதுவரை use பண்ணாத modules உட்பட.
partial(pow, exp=2) உங்களுக்கு என்ன தரும்?
இப்போ இதை செஞ்சு பாருங்க
- max() இல்லாம reduce வெச்சு list-ல பெரிய எண்ணை கண்டுபிடிச்சு, max()-ஓட compare பண்ணுங்க.
- Interactive prompt-ல
dir(str)வெச்சுstrtype-ஐ ஆராய்ஞ்சு, இதுவரை use பண்ணாத மூணு methods-ஐ தேர்ந்தெடுத்து அதோடhelp()-ஐ படிங்க.
Create a free account to save your progress, or sign in.