Decorator Design Pattern
Videos
| Section | Video Links |
|---|---|
| Decorator Overview | ![]() |
| Decorator Use Case | ![]() |
| _str_ Dunder Method | ![]() |
| Python getattr() Method | ![]() |
Book
Overview
... Refer to Book, pause Video Lectures or subscribe to Medium Membership to read textual content.
Terminology
... Refer to Book, pause Video Lectures or subscribe to Medium Membership to read textual content.
Builder UML Diagram
Output
python ./decorator/decorator_concept.py Component Method Decorator Method(Component Method)
Example Use Case
... Refer to Book, pause Video Lectures or subscribe to Medium Membership to read textual content.
Example UML Diagram
Output
python ./decorator/client.py 3 101 4 6 -1 106 113 114 1 2 5
New Coding Concepts
Python getattr() Function
Syntax: getattr(object, attribute, default)
In the Sub and Add classes, I use the getattr() method like a ternary operator.
When initializing the Add or Sub classes, you have the option of providing an integer or an existing instance of the Value, Sub or Add classes.
So, for example, the line in the Sub class,
val1 = getattr(val1, 'value', val1)
is saying, if the val1 just passed into the function already has an attribute value, then val1 must be an object of Value, Sub or Add . Otherwise, the val1 that was passed in is a new integer and it will use that instead to calculate the final value of the instance on the next few lines of code. This behavior allows the Sub and Add classes to be used recursively.
E.g.,
A = Value(2) Add(Sub(Add(200, 15), A), 100)
Dunder __str__ method
When you print() an object, it will print out the objects type and memory location in hex.
class ExampleClass: abc = 123 print(ExampleClass())
Outputs
<__main__.ExampleClass object at 0x00000283038B1D00>
You can change this default output by implementing the __str__ dunder method in your class. Dunder is short for saying double underscore.
Dunder methods are predefined methods in python that you can override with your own implementations.
class ExampleClass: abc = 123 def __str__(self): return "Something different" print(ExampleClass())
Now outputs
In all the classes in the above use case example that implement the IValue interface, the __str__ method is overridden to return a string version of the integer value. This allows to print the numerical value of any object that implements the IValue interface rather than printing a string that resembles something like below.
<__main__.ValueClass object at 0x00000283038B1D00>
The __str__ dunder was also overridden in the /prototype/prototype_concept.py concept code.
Summary
... Refer to Book, pause Video Lectures or subscribe to Medium Membership to read textual content.



