Python Design Patterns 1
Why Stack Overflow recommends it
Stack Overflow users link it when someone asks about design patterns, abstract base classes or polymorphism in Python and needs a broader grounding than a single answer can give.
Recommended by 2 people across 2 different months, 2012 to 2021.
What it is
A PyCon talk by Brandon Rhodes that uses simple one-slide Python programs to show how classic design patterns and refactorings apply to Python. It covers how duck typing and Python's own features make some patterns trivial while others, like adapters, remain useful.
What people said
Recommends Sebastian Wozny · 2015-11 · Stack Overflow · on “Python: Using eval() in class / different methods of case distinction”
Your question is very broad and you're probably better off watching a talk on polymorphism [LINK] and the super [LINK] function(behaviour distinction without if ) or python design patterns [this video] . For the specific problem you posted you want to use getattr [LINK] : getattr(object, name[, default]) Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar . If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. class thing: def __init__(self, inp, inp2): self.aT
Recommends adam.hendry · 2021-11 · Stack Overflow · on “Why use Abstract Base Classes in Python?”
ABC's enable design patterns and frameworks to be created. Please see this pycon talk by Brandon Rhodes: Python Design Patterns 1 [this video] The protocols within Python itself (not to mention iterators, decorators, and slots (which themselves implement the FlyWeight pattern)) are all possible because of ABC's (albeit implemented as virtual methods/classes in CPython). Duck typing does make some patterns trivial in python, which Brandon mentions, but many other patterns continue to pop up and be useful in Python, e.g. Adapters. In short, ABC's enable you to write scalable and reusable code. Per the GoF: Program to an interface, not an implementation (inheritance breaks encapsulation; programming
Cites root · 2012-10 · Stack Overflow · on “Design patterns: Continue”
If you define a pattern as a clever trick that helps you solve a programming problem in an elegant and perhaps more readable way [1] [this video] . What are the design patterns for using the continue statement (if one is avoiding deeply nested if statements)? for item in items: if is_for_sale(item): cost=compute_cost(item) if cost<=wallet.money: buy(item) for item in items: if not is_for_sale(item): continue cost = compute_cost(item) if cost > wallet.money: continue buy(item)