In this example, we factored the __init__() method into the superclass so that a common initialization in the superclass, Card, applies to all the three subclasses NumberCard, AceCard, and FaceCard.
DDaudalagidhar citeretfor 2 år siden
A small domain of static objects may be part of implementing a Strategy or State design pattern. In some cases, we may have a pool of constant objects created in an initialization or configuration file, or we might create constant objects based on command-line parameters.
DDaudalagidhar citeretfor 2 år siden
This can make the Strategy or State design patterns work efficiently by reusing objects from a small, static pool of constants.
DDaudalagidhar citeretfor 2 år siden
We define a function that creates objects of the required classes. We define a class that has methods for creating objects. This is the full factory design pattern, as described in books on design patterns. In languages such as Java, a factory class hierarchy is required because the language doesn't support standalone functions.
DDaudalagidhar citeretfor 2 år siden
The advantage of class definitions in general is to achieve code reuse via inheritance.
DDaudalagidhar citeretfor 2 år siden
If the alternative factory definitions don't actually reuse any code, then a class hierarchy won't be helpful in Python. We can simply use functions that have the same signatures.
DDaudalagidhar citeretfor 2 år siden
On the one hand, it can be argued that the condition that belongs on an else clause should never be left unstated because it may hide subtle design errors. On the other hand, some else clause conditions are truly obvious. It's important to avoid the vague else clause.
DDaudalagidhar citeretfor 2 år siden
When to use catch-all else Rarely. Use it only when the condition is obvious. When in doubt, be explicit and use else to raise an exception. Avoid the vague else clause.
DDaudalagidhar citeretfor 2 år siden
In some cases, we can use a mapping instead of a chain of elif conditions. It's possible to find conditions that are so complex that a chain of elif conditions is the only sensible way to express them. For simple cases, however, a mapping often works better and can be easy to read.
fb2epub
Træk og slip dine filer
(ikke mere end 5 ad gangen)