In the previous episodes
- basic stuff, syntax
- functions (wrote our cool min function) + functional stuff
- scopes
- PEP-8
- strings
- bytes
- collections
🏛 Classes basics
👇 Class
Welcome, self keyword
Attributes: object and class (like in other languages)
㊙ Private attributes
🔖 dict attributes
👀 slots
Reduce memory usage!
🔗 Bounded and unbounded methods
@property
🍩 more @property
👩👧👧 Inheritance
Search for values/methods:
object ➡️ class ➡️ base classes
👨👦👦 Inheritance
☑️ isinstance() predicate
☑️ issubclass() predicate
🎭 Do not overcomplicate with inheritance
In case you are wondering how search for methods in subclasses works:
https://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/
Mixin
But we have decorators!
🏛 Classes basics wrap-up
🏵 Decorators
Decorator is a function that gets a function and returns smth
==
🚲 Let’s write a decorator
Problem – we forgot old metadata
Let’s fix it!
This could be done simpler
Or even more simple
🚲 Let’s add some config flag
Important reminder
==
So
==
👀 We need to go deeper
decorator with arguments
and we can make another decorator
🚲 We did it again
Questions?
How about default variable?
The solution
Same, but simpler
What’s *
for?
😎 Practical decorators
@timethis
@once
@memoized
Ooops…
The solution
@deprecated
@pre
@post
You can apply multiple decorators, but the order matters
🏵 Decorators wrap-up
- they are useful if you want to simplify your code
- they can be difficult sometimes
- use default solutions
More decorator examples – https://wiki.python.org/moin/PythonDecoratorLibrary
🤙 @lru_cache
🤘 partial
🤌 singledispatch
🤏 reduce
motivation
…with the help of reduce we can
By the way, not so popular in Python!
🏁 Any questions?