Visitor Design Pattern
Videos
| Section | Video Links |
|---|---|
| Visitor Overview | ![]() |
| Visitor Use Case | ![]() |
| hasattr() Method | ![]() |
| expandtabs() 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.
Visitor UML Diagram
Source Code
... Refer to Book, pause Video Lectures or subscribe to Medium Membership to read textual content.
Output
python ./visitor/visitor_concept.py D B C A 561
Visitor Example Use Case
... Refer to Book, pause Video Lectures or subscribe to Medium Membership to read textual content.
Visitor Example UML Diagram
Output
python ./visitor/client.py Utility :ABC-123-21 V8 engine :DEF-456-21 FrontLeft :GHI-789FL-21 FrontRight :GHI-789FR-21 BackLeft :GHI-789BL-21 BackRight :GHI-789BR-21 Total Price = 4132
New Coding Concepts
Instance hasattr()
In the Visitor objects in the example use case above, I test if the elements have a certain attribute during the visit operation.
def visit(cls, element): if hasattr(element, 'price'): ...
The hasattr() method can be used to test if an instantiated object has an attribute of a particular name.
class ClassA(): name = "abc" value = 123 CLASS_A = ClassA() print(hasattr(CLASS_A, "name")) print(hasattr(CLASS_A, "value")) print(hasattr(CLASS_A, "date"))
Outputs
String expandtabs()
When printing strings to the console, you can include special characters \t that print a series of extra spaces called tabs. The tabs help present multiline text in a more tabular form which appears to be neater to look at.
abc 123 defg 456 hi 78910
The number of spaces added depends on the size of the word before the \t character in the string. By default, a tab makes up 8 spaces.
Now, not all words separated by a tab will line up the same on the next line.
abcdef 123 cdefghij 4563 ghi 789 jklmn 1011
The problem occurs usually when a word is already 8 or more characters long.
To help solve the spacing issue, you can use the expandtabs() method on a string to set how many characters a tab will use.
print("abcdef\t123".expandtabs(10)) print("cdefghij\t4563".expandtabs(10)) print("ghi\t789".expandtabs(10)) print("jklmn\t1011".expandtabs(10))
Now outputs
abcdef 123 cdefghij 4563 ghi 789 jklmn 1011
Summary
... Refer to Book, pause Video Lectures or subscribe to Medium Membership to read textual content.



